tgoop.com/fullStackDevs/480
Last Update:
#ادامه
#Keyless_Entity
🔹مثال
ابتدا مدل های زیر را تعریف میکنیم
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
}
▪️در خط زیر نیست یک view ساده در دیتابیس تعریف میکتیم که هر Post به همراه Blog مرتبطش برمیگرداند.
db.Database.ExecuteSqlRaw(
@"CREATE VIEW View_BlogPostCounts AS
);
SELECT b.Name, Count(p.PostId) as PostCount
FROM Blogs b
JOIN Posts p on p.BlogId = b.BlogId
GROUP BY b.Name"
▪️در نهایت Keyless Entity خود را متناظر با نوع خروچی View ای که ساختیم به اینصورت تعریف میکنیم.
public class BlogPostsCount
{
public string BlogName { get; set; }
public int PostCount { get; set; }
}
▪️و آنرا بدین شکل در متد OnModelCreating کانفیگ میکنیم.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
eb.HasNoKey();
.Entity<BlogPostsCount>(eb =>
{
eb.ToView("View_BlogPostCounts");
eb.Property(v => v.BlogName).HasColumnName("Name"); });
}
▪️ حال نوبت به معرفی کرد keyless Entity به DbContext میباشد.که بدین شکل در Db Context تعریف میشودpublic DbQuery<BlogPostsCount> BlogPostCounts { get; set; }
در آخر نیز بدین شکل میتوانید از آن استفاده کنید.
var postCounts = db.BlogPostCounts.ToList();
foreach (var postCount in postCounts)
{
Console.WriteLine($"{postCount.BlogName} has {postCount.PostCount} posts.");
Console.WriteLine();
}
لینک منبع
🔹سورس این پست رو در اینجا بررسی کنید.
@FullStackDevs
BY Web Devs
Share with your friend now:
tgoop.com/fullStackDevs/480