具有一对一关系和一对一关系的实体-设置外键

时间:2019-05-24 07:02:41

标签: c# asp.net-core entity-framework-core

我有这个简单的模型,我想配置它们之间的关系

一个公司有一个徽标

一个公司可以有很多文件

public class Company
{
    public int Id { get; set; }

    public File Logo { get; set; }

    public List<File> Attachments { get; set; } = new List<File>();
}

public class File
{
    public int Id { get; set; }

    public Company Company { get; set; }

    public int CompanyId { get; set; }  

    (...)
}

public class CompanyConfiguration : IEntityTypeConfiguration<Company>
{
    public void Configure(EntityTypeBuilder<Company> builder)
    {
        builder
            .HasMany(x => x.Attachments)
            .WithOne(x => x.Company)
            .HasForeignKey(x => x.CompanyId);

        builder
           .HasOne(x => x.Logo)
           .WithOne(x => x.Company)
           .HasForeignKey(x => x.); // x. doesnt show me anything about "File" class. It looks like assembly

    }
}

但是由于我可能只需要两个FK

我将其更改为:

public class File
{
    public int Id { get; set; }

    public Company Company { get; set; }
    public int CompanyId { get; set; }  

    public Company CompanyOtherProperty { get; set; }
    public int CompanyOtherPropertyId { get; set; }
}

但是即使我将FK的名称作为字符串插入

public class CompanyConfiguration : IEntityTypeConfiguration<Company>
{
    public void Configure(EntityTypeBuilder<Company> builder)
    {
        builder
            .HasMany(x => x.Attachments)
            .WithOne(x => x.Company)
            .HasForeignKey(x => x.CompanyId);

        builder
           .HasOne(x => x.Logo)
           .WithOne(x => x.CompanyOtherProperty)
           .HasForeignKey("CompanyOtherPropertyId");
    }
}
  

System.InvalidOperationException:'您正在配置'Company'和'File'之间的关系,但是在'CompanyOtherPropertyId'上指定了外键。外键必须在属于关系的类型上定义。'

2 个答案:

答案 0 :(得分:1)

鉴于您的需求,由于徽标和附件具有相同的属性但关系不相同,因此我将使用继承来进行此操作

public abstract class File
{
    public int Id { get; set; }
    .....
}

public class Logo : File
{
    ....
}

public class Attachement : File
{
    public Company Company { get; set; }

    public int CompanyId { get; set; }
}

public class Company
{
    public int Id { get; set; }

    public Logo Logo { get; set; }

    public int LogoId { get; set; }

    public ICollection<Attachement> Attachements { get; set; } = new List<Attachement>();

}
public DbSet<Company> Companies { get; set; }

public DbSet<Attachement> Attachements { get; set; }

public DbSet<Logo> Logos { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<File>().HasDiscriminator();
}

答案 1 :(得分:0)

您现在拥有的设计容易出错,我假设一个文件不能同时是徽标和附件,这意味着两个公司导航属性之一将始终为null。您将不得不在系统中的所有地方进行空检查

对于FileLogo,您应该有单独的模型