简体   繁体   English

在EF7中添加相同类型的多个导航属性

[英]Adding multiple navigation properties of the same type in EF7

I have a model that looks like this 我有一个看起来像这样的模型

public class Issue
{
    public Guid Id { get; set; }

    [Required]
    public User ReportedByUser { get; set; }

    public User ClosedByUser { get; set; }

    public Category Category { get; set; }
}

However, when I run ef migrations add <MigrationName> I am getting the following error: 但是,当我运行ef migrations add <MigrationName>我收到以下错误:

The navigation 'ReportedByUser' on entity type 'WebProject.Models.Issue' has not been added to the model, or ignored, or target entityType ignored. 实体类型'WebProject.Models.Issue'上的导航'ReportedByUser'尚未添加到模型中,或被忽略,或者目标entityType被忽略。

I do not get this error when I only have 1 navigational property of type User in the model. 当我在模型中只有一个User类型的导航属性时,我没有收到此错误。 How do I make this work with the model above? 如何使用上述模型进行此操作?

It will better for you to explicitly declare the foreign keys properties when you do code first with migrations. 首先使用迁移进行代码时,最好显式声明外键属性。 Also if you stick to the convention ReferencePropertyName + Id for this property, you do not have to decorate the class with ForeignKeyAttribute as EF will resolve it for you. 此外,如果您坚持使用此属性的约定ReferencePropertyName + Id ,则不必使用ForeignKeyAttribute来装饰该类,因为EF将为您解析它。

public class Issue
{
        public Guid Id { get; set; }   

        public Guid ReportedByUserId { get; set; }
        public User ReportedByUser { get; set; }

        public Guid ClosedByUserId { get; set; }
        public User ClosedByUser { get; set; }    
}

I was able to fix this by setting up the following relationships in my DbContext. 我能够通过在我的DbContext中设置以下关系来解决这个问题。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Issue>()
            .HasOne(i => i.ReportedByUser)
            .WithMany(u => u.Issues)
            .OnDelete(DeleteBehavior.Restrict);

        modelBuilder.Entity<Issue>()
                .HasOne(i => i.ClosedByUser)
                .WithMany(u => u.Issues)
                .OnDelete(DeleteBehavior.Restrict).IsRequired(false);

        base.OnModelCreating(modelBuilder);
    }

And setting up the model like below. 并设置如下模型。

public class Issue
{
    public Guid Id { get; set; }   
    [Required]        
    public User ReportedByUser { get; set; }        
    public User ClosedByUser { get; set; }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM