一、多导航属性配型
public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public User Author { get; set; } public User Contributor { get; set; } } public class User { public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [InverseProperty(nameof(Post.Author))] //设置反转导航属性 public List<Post> AuthoredPosts { get; set; } [InverseProperty(nameof(Post.Contributor))] //设置反转导航属性 public List<Post> ContributedToPosts { get; set; } }
在Post类设置反转导航属性也可以
public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; }
[InverseProperty(nameof(User.AuthoredPosts))] public User Author { get; set; }
[InverseProperty(nameof(User.ContributedToPosts))] public User Contributor { get; set; } } public class User { public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List<Post> AuthoredPosts { get; set; } public List<Post> ContributedToPosts { get; set; } }
Post表会默认生成:“导航属性名Id” 的外键 AuthorId,ContributorId
public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public User Author { get; set; } public User Contributor { get; set; } } public class User { public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public User Author { get; set; } [ForeignKey("AuthorID")] public string ContributorID { get; set; } [ForeignKey("ContributorID")] public User Contributor { get; set; } }
3.Fluent API方式
modelBuilder.Entity<Post>().HasOne(p => p.Author).WithMany(u=>u.AuthoredPosts).HasForeignKey("AuthorId"); modelBuilder.Entity<Post>().HasOne(p => p.Contributor).WithMany(u => u.ContributedToPosts);
二、Fluent API显示设置外键
referenceCollectionBuilder.HasForeignKey(p => p.BlogForeignKey); modelBuilder.Entity<Car>().HasKey(c => new { c.State, c.LicensePlate }); referenceCollectionBuilder.HasFoHasForeignKey(s => new { s.CarState, s.CarLicensePlate }) //设置有复合主键表的外键,依赖主体要定义CarState,CarLicensePlate 这两个复合主键的属性字段 referenceCollectionBuilder.HasForeignKey("BlogId");
原文:https://www.cnblogs.com/Adoni/p/12300357.html