一、多导航属性配型
在 Post 类中,可能需要跟踪是文章的创建者和最后编辑者,下面是 Post 类的两个新的导航属性。
1、设置导航属性方式
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
2.ForeignKeyAttribute方式设置
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");