首页 > 其他 > 详细

7. EF Core 多导航属性配置

时间:2020-02-12 21:35:12      阅读:539      评论:0      收藏:0      [点我收藏+]

一、多导航属性配型

在 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");

 

7. EF Core 多导航属性配置

原文:https://www.cnblogs.com/Adoni/p/12300357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!