发布:2023/12/7 15:32:06作者:大数据 来源:大数据 浏览次数:548
一对一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogImage BlogImage { get; set; } } public class BlogImage { public int BlogImageId { get; set; } public byte[] Image { get; set; } public string Caption { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } |
一对多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<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; } public Blog Blog { get; set; } } |
多对多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } } public class Tag { public string TagId { get; set; } public List<PostTag> PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public string TagId { get; set; } public Tag Tag { get; set; } } |
关于包含include说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class Product { public int Id { get; set; } public string BarCode { get; set; } public int CategoryId { get; set; } = 0; public Category Category { get; set; } public Clothing Clothing { get; set; } } public class Category { public int Id { get; set; } public string CategoryName { get; set; } } public class Clothing { public int Id { get; set; } public string Brand { get; set; } public int ProductId { get; set; } = 0; public Product Product { get; set; } } |
Product与Category和Clothing都是一对一关系,只是导航属性不同。
如果Product访问Clothing需要使用Include包含进来,否则Clothing为空,而Category同理。
var q=dbcontext.Product;//可访问关联的Category表信息而Clothing=null
var q=dbcontext.Product.Include(p=>p.Clothing);//可Category=null和Cloning关联的信息
var q=dbcontext.Product.Include(p => p.Clothing).Include(p=>p.Category);//这样就关联起来了。
参考:https://docs.microsoft.com/zh-cn/ef/core/modeling/relationships
© Copyright 2014 - 2025 柏港建站平台 ejk5.com. 渝ICP备16000791号-4