Skip to content

Commit 177134a

Browse files
committed
another resuggest
1 parent 5293f9c commit 177134a

File tree

11 files changed

+1179
-84
lines changed

11 files changed

+1179
-84
lines changed

BookStore.DAL.EntityFramework/EfAuthorRepository.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public override void Save(Author auth)
5757
{
5858
using (EfDbContext context = new EfDbContext())
5959
{
60-
Author authStore = context.Authors.FirstOrDefault(a => a.Author_ID == auth.Author_ID);
60+
Author authStore = context.Authors.Include(x=>x.AuthorDetail).FirstOrDefault(a => a.Author_ID == auth.Author_ID);
6161
if (authStore == null)
6262
{
6363
context.Authors.Add(auth);

BookStore.DAL.EntityFramework/EfBookRepository.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public override void Save(Book obj)
124124
{
125125
using (EfDbContext context = new EfDbContext())
126126
{
127-
Book bookForSave = context.Books.FirstOrDefault(b => b.Book_ID == obj.Book_ID);
127+
Book bookForSave = context.Books.Include(x=>x.BookAuthors).Include(x=>x.BookDetail.Tages).Include(x=>x.BookDetail.Genres).FirstOrDefault(b => b.Book_ID == obj.Book_ID);
128128
if (bookForSave == null)
129129
{
130130
context.Books.Add(obj);

BookStore.DAL.EntityFramework/EfDbContext.cs

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using BookStore.DO.Entities;
22
using System.Data.Entity;
3+
using System.Net.Configuration;
34

45
namespace BookStore.DAL.EntityFramework
56
{
@@ -8,7 +9,10 @@ public class EfDbContext : DbContext
89
public EfDbContext()
910
: base()
1011
{
11-
//this.Configuration.LazyLoadingEnabled = false;
12+
13+
this.Configuration.LazyLoadingEnabled = false;
14+
Configuration.ProxyCreationEnabled = false;
15+
1216
}
1317
public DbSet<Book> Books { get; set; }
1418
public DbSet<BookDetail> BookDetails { get; set; }
@@ -47,6 +51,9 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder)
4751
.HasMany(c => c.BookAuthors).WithMany(i => i.Books)
4852
.Map(t => t.MapLeftKey("Book_ID")
4953
.MapRightKey("Author_ID"));
54+
55+
//modelBuilder.Entity<Rate>().HasRequired(x => x.User);
56+
//modelBuilder.Entity<Rate>().HasRequired(x => x.Book);
5057
}
5158
}
5259
}

BookStore.DAL.EntityFramework/EfUserRepository.cs

+89-77
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public override User GetById(int id)
1717
{
1818
using (EfDbContext context = new EfDbContext())
1919
{
20-
return context.Users.Include(x=>x.Profile.Comments).FirstOrDefault(x=>x.User_ID==id);
20+
return context.Users.Include(x => x.Profile.Comments).FirstOrDefault(x => x.User_ID == id);
2121
}
2222
}
2323

@@ -48,7 +48,7 @@ public IList<Role> GetRoles(int userId)
4848
{
4949
using (EfDbContext context = new EfDbContext())
5050
{
51-
return context.Users.FirstOrDefault(u => u.User_ID == userId).Roles.ToList();
51+
return context.Users.Include(x=>x.Roles).FirstOrDefault(u => u.User_ID == userId).Roles.ToList();
5252
}
5353
}
5454

@@ -62,11 +62,11 @@ public User GetUserByEmail(string email)
6262

6363
using (EfDbContext context = new EfDbContext())
6464
{
65-
return context.Users.Include(x=>x.Profile)
65+
return context.Users.Include(x => x.Profile)
6666
.Include(e => e.Roles)
67-
.Include(x => x.Profile.WishedBooks.Select(c=>c.Book.BookAuthors))
67+
.Include(x => x.Profile.WishedBooks.Select(c => c.Book.BookAuthors))
6868
.Include(x => x.Profile.RatedBooks.Select(b => b.Book.Book.BookAuthors))
69-
.Include(x => x.Profile.FavoriteAuthors.Select(c=>c.Author))
69+
.Include(x => x.Profile.FavoriteAuthors.Select(c => c.Author))
7070
.FirstOrDefault(e => e.Email == email);
7171
}
7272
}
@@ -80,7 +80,7 @@ public async Task RateBook(float rate, int userId, int bookId, bool isSuggestion
8080
Book book = context.Books.FirstOrDefault(x => x.Book_ID == bookId);
8181
Rate rating = context.Rates.
8282
FirstOrDefault(x => x.User.User_ID == userId && x.Book.Book_ID == bookId) ??
83-
new Rate() { User=context.Users.FirstOrDefault(x=>x.User_ID==userId).Profile };
83+
new Rate() { User = context.Users.FirstOrDefault(x => x.User_ID == userId).Profile };
8484
rating.RateValue = rate;
8585
rating.IsSuggestion = isSuggestion;
8686
book.BookDetail.RatedUsers.Add(rating);
@@ -132,19 +132,22 @@ public override void Create(User obj)
132132
user.Users.Add(obj);
133133
context.SaveChanges();
134134
}
135-
}
135+
}
136136

137-
public void Suggest(float rate, int userId, int bookId, bool isSuggestion)
137+
public void Suggest(float rate, int userId, int bookId, bool isSuggestion)
138138
{
139139
using (EfDbContext context = new EfDbContext())
140140
{
141-
Book book = context.Books.FirstOrDefault(x => x.Book_ID == bookId);
142141
Rate rating = context.Rates.
143142
FirstOrDefault(x => x.User.User_ID == userId && x.Book.Book_ID == bookId) ??
144-
new Rate() {User = context.Users.FirstOrDefault(x=>x.User_ID==userId).Profile};
143+
new Rate()
144+
{
145+
User = context.Users.Include(x => x.Profile).FirstOrDefault(x => x.User_ID == userId).Profile,
146+
Book = context.Books.Include(x => x.BookDetail).FirstOrDefault(x => x.Book_ID == bookId).BookDetail
147+
};
145148
rating.RateValue = rate;
146149
rating.IsSuggestion = isSuggestion;
147-
book.BookDetail.RatedUsers.Add(rating);
150+
context.Rates.Add(rating);
148151
context.SaveChanges();
149152
}
150153
}
@@ -186,7 +189,7 @@ public void Resuggest()
186189
else
187190
{
188191
matr[i][j] =
189-
(new Rate { User = context.Users.FirstOrDefault(x=>x.User_ID==user.Value.User_ID).Profile, Book = new BookDetail() { Book_ID = books[j].Book_ID } });
192+
(new Rate { User = context.Users.FirstOrDefault(x => x.User_ID == user.Value.User_ID).Profile, Book = new BookDetail() { Book_ID = books[j].Book_ID } });
190193
}
191194
}
192195
}
@@ -273,91 +276,100 @@ public void Resuggest()
273276

274277
public void Resuggest1()
275278
{
279+
List<Rate> dbRates = new List<Rate>();
276280
using (EfDbContext context = new EfDbContext())
277281
{
278-
var users = context.Users.Include(x=>x.Profile.RatedBooks).ToList();
279-
var books = context.Books.Include(x=>x.BookDetail.RatedUsers).ToList();
280-
int maxBookId =context.Books.Select(x => x.Book_ID).Max();
281-
float[,] matrix = new float[users.Count, books.Count];
282-
float[,] result = new float[users.Count, books.Count];
283-
Rate[,] matr = new Rate[users.Count, books.Count];
284-
int rateCounter = 0;
285-
//int[,] korelation = new int[users.Count, users.Count];
286-
float[,] corelation = new float[users.Count, users.Count];
287-
//List<double> corelation = new List<double>();
288-
List<float> average = new List<float>();
289-
List<float> diff = new List<float>();
290-
for (int i = 0; i < users.Count; i++)
282+
dbRates = context.Rates.Include(i => i.Book).Include(i => i.User).ToList();
283+
}
284+
HashSet<int> bookIds = new HashSet<int>();
285+
HashSet<int> userIds = new HashSet<int>();
286+
foreach (var dbRate in dbRates)
287+
{
288+
if (!bookIds.Contains(dbRate.Book.Book_ID))
291289
{
292-
var rates = users[i].Profile.RatedBooks.Where(x => x.IsSuggestion == false).ToList();
293-
float averageRate = 0;
294-
int countNonZero = 0;
295-
for (int j = 0; j < books.Count; j++)
290+
bookIds.Add(dbRate.Book.Book_ID);
291+
}
292+
if (!userIds.Contains(dbRate.User.User_ID))
293+
{
294+
userIds.Add(dbRate.User.User_ID);
295+
}
296+
}
297+
float[,] result = new float[userIds.Count, bookIds.Count];
298+
Rate[,] matr = new Rate[userIds.Count, bookIds.Count];
299+
int rateCounter = 0;
300+
float[,] corelation = new float[userIds.Count, userIds.Count];
301+
List<float> average = new List<float>();
302+
List<float> diff = new List<float>();
303+
for (int i = 0; i < userIds.Count; i++)
304+
{
305+
float averageRate = 0;
306+
int countNonZero = 0;
307+
for (int j = 0; j < bookIds.Count; j++)
308+
{
309+
var rate = dbRates.FirstOrDefault(x => x.IsSuggestion == false && x.Book.Book_ID == bookIds.ElementAt(j) && x.User.User_ID == userIds.ElementAt(i));
310+
if (rate != null)
296311
{
297-
var rate = rates.FirstOrDefault(x => x.Book.Book_ID == books[j].Book_ID);
298-
if (rate != null)
299-
{
300-
matr[i,j] = rate;
301-
rateCounter++;
302-
averageRate += rate.RateValue;
303-
countNonZero++;
304-
average.Add(averageRate / countNonZero);
305-
}
306-
else
307-
{
308-
matr[i,j] =
309-
(new Rate { User = users[i].Profile,IsSuggestion = true,Book = books[j].BookDetail });
310-
}
312+
matr[i, j] = rate;
313+
rateCounter++;
314+
averageRate += rate.RateValue;
315+
countNonZero++;
316+
average.Add(averageRate / countNonZero);
317+
}
318+
else
319+
{
320+
matr[i, j] =
321+
(new Rate { IsSuggestion = true });
311322
}
312-
if (i> 0)
323+
}
324+
if (i > 0)
325+
{
326+
for (int k = 1; k <= i; k++) //ïî þçåðàì
313327
{
314-
for (int k = 1; k<= i; k++) //ïî þçåðàì
328+
double kor = 0;
329+
float sum = 0, sumSquare1 = 0, sumSquare2 = 0;
330+
for (int j = 0; j < bookIds.Count; j++) //ïî êíèæêàì
315331
{
316-
double kor = 0;
317-
float sum = 0, sumSquare1 = 0, sumSquare2 = 0;
318-
for (int j = 0; j < books.Count; j++) //ïî êíèæêàì
332+
if (!matr[i, j].IsSuggestion && !matr[i - k, j].IsSuggestion)
319333
{
320-
if (!matr[i, j].IsSuggestion && !matr[i - k, j].IsSuggestion)
321-
{
322-
sum += (matr[i, j].RateValue - average.ElementAt(i)) *
323-
(matr[i - k, j].RateValue - average.ElementAt(i - k));
324-
sumSquare1 += (matr[i, j].RateValue - average.ElementAt(i)) *
325-
(matr[i, j].RateValue - average.ElementAt(i));
326-
sumSquare2 += (matr[i - k, j].RateValue - average.ElementAt(i - k)) *
327-
(matr[i - k, j].RateValue - average.ElementAt(i - k));
328-
}
334+
sum += (matr[i, j].RateValue - average.ElementAt(i)) *
335+
(matr[i - k, j].RateValue - average.ElementAt(i - k));
336+
sumSquare1 += (matr[i, j].RateValue - average.ElementAt(i)) *
337+
(matr[i, j].RateValue - average.ElementAt(i));
338+
sumSquare2 += (matr[i - k, j].RateValue - average.ElementAt(i - k)) *
339+
(matr[i - k, j].RateValue - average.ElementAt(i - k));
329340
}
330-
diff.Add(sumSquare1);
331-
kor = sum / (Math.Sqrt(sumSquare1) * Math.Sqrt(sumSquare2));
332-
corelation[i, i - k] =corelation[i - k, i] = (float)kor;
333341
}
342+
diff.Add(sumSquare1);
343+
kor = sum / (Math.Sqrt(sumSquare1) * Math.Sqrt(sumSquare2));
344+
corelation[i, i - k] = corelation[i - k, i] = (float)kor;
334345
}
335346
}
336-
Rate[,] SubMatrix = (Rate[,]) matr.Clone();
337-
for (int i = 0; i < SubMatrix.GetLength(0); i++)
347+
}
348+
Rate[,] subMatrix = (Rate[,])matr.Clone();
349+
for (int i = 0; i < subMatrix.GetLength(0); i++)
350+
{
351+
for (int j = 0; j < subMatrix.GetLength(1); j++)
338352
{
339-
for (int j = 0; j < SubMatrix.GetLength(1); j++)
353+
if (subMatrix[i, j].IsSuggestion)
340354
{
341-
if (SubMatrix[i, j].IsSuggestion)
355+
float sum = 0;
356+
float sumCor = 0;
357+
for (int k = 0; k < subMatrix.GetLength(0); k++)
342358
{
343-
float sum = 0;
344-
float sumCor = 0;
345-
for (int k = 0; k < SubMatrix.GetLength(0); k++)
346-
{
347-
if (!SubMatrix[k, j] .IsSuggestion&& !float.IsNaN(average[k]))
348-
{
349-
sum += (SubMatrix[k, j].RateValue - average[k])*corelation[k, i];
350-
sumCor += Math.Abs(corelation[k, i]);
351-
}
352-
}
353-
if (sum != 0 && !float.IsNaN(sum))
359+
if (!subMatrix[k, j].IsSuggestion && !float.IsNaN(average[k]))
354360
{
355-
Suggest((average[i] + sum / sumCor) > 10 ? 10 : (average[i] + sum / sumCor), users[i].User_ID, books[j].Book_ID, true);
356-
result[i, j] = average[i] + sum/sumCor;
361+
sum += (subMatrix[k, j].RateValue - average[k]) * corelation[k, i];
362+
sumCor += Math.Abs(corelation[k, i]);
357363
}
358364
}
365+
if (sum != 0 && !float.IsNaN(sum))
366+
{
367+
Suggest((average[i] + sum / sumCor) > 10 ? 10 : (average[i] + sum / sumCor), userIds.ElementAt(i), bookIds.ElementAt(j), true);
368+
result[i, j] = average[i] + sum / sumCor;
369+
}
359370
}
360371
}
372+
361373
}
362374
}
363375
}

BookStore.Domain/Entities/Author.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public class AuthorDetail
4242
public string Image_url { get; set; }
4343
[Display(Name = "Биография")]
4444
[AllowHtml]
45-
[MaxLength(10000)]
45+
[MaxLength(20000)]
4646
public string Biography { get; set; }
4747

4848
public virtual ICollection<UserProfile> FavoriteUsers { get; set; }

BookStore.Tests/BookStore.Tests.csproj

+11-1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@
3737
<WarningLevel>4</WarningLevel>
3838
</PropertyGroup>
3939
<ItemGroup>
40+
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
41+
<SpecificVersion>False</SpecificVersion>
42+
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
43+
</Reference>
44+
<Reference Include="EntityFramework.SqlServer">
45+
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll</HintPath>
46+
</Reference>
4047
<Reference Include="Moq">
4148
<HintPath>..\packages\Moq.4.2.1502.0911\lib\net40\Moq.dll</HintPath>
4249
</Reference>
@@ -45,6 +52,7 @@
4552
<HintPath>..\packages\Ninject.3.2.2.0\lib\net45-full\Ninject.dll</HintPath>
4653
</Reference>
4754
<Reference Include="System" />
55+
<Reference Include="System.ComponentModel.DataAnnotations" />
4856
<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
4957
<SpecificVersion>False</SpecificVersion>
5058
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
@@ -96,7 +104,9 @@
96104
</ProjectReference>
97105
</ItemGroup>
98106
<ItemGroup>
99-
<None Include="app.config" />
107+
<None Include="app.config">
108+
<SubType>Designer</SubType>
109+
</None>
100110
<None Include="packages.config" />
101111
</ItemGroup>
102112
<Choose>

BookStore.Tests/UnitTest1.cs

+9
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Web.Mvc;
66
using Microsoft.VisualStudio.TestTools.UnitTesting;
77
using BookStore.Controllers;
8+
using BookStore.DAL.EntityFramework;
89
using BookStore.DLL.Interface.Abstract;
910
using BookStore.DO.Entities;
1011
using BookStore.Models;
@@ -54,5 +55,13 @@ public void List()
5455
// Assert
5556
Assert.IsNotNull(result);
5657
}
58+
59+
[TestMethod]
60+
public void TestRates()
61+
{
62+
var userRepository = new EfUserRepository();
63+
64+
userRepository.Resuggest1();
65+
}
5766
}
5867
}

BookStore.Tests/app.config

+18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<configuration>
3+
<configSections>
4+
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
5+
6+
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
7+
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
8+
<connectionStrings>
9+
<add name="EfDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Book; Integrated Security=True" providerName="System.Data.SqlClient" />
10+
</connectionStrings>
311
<runtime>
412
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
513
<dependentAssembly>
@@ -8,4 +16,14 @@
816
</dependentAssembly>
917
</assemblyBinding>
1018
</runtime>
19+
<entityFramework>
20+
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
21+
<parameters>
22+
<parameter value="v11.0" />
23+
</parameters>
24+
</defaultConnectionFactory>
25+
<providers>
26+
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
27+
</providers>
28+
</entityFramework>
1129
</configuration>

BookStore.Tests/packages.config

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<packages>
3+
<package id="EntityFramework" version="6.1.3" targetFramework="net45" />
34
<package id="Moq" version="4.2.1502.0911" targetFramework="net45" />
45
<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
56
</packages>

0 commit comments

Comments
 (0)