EF Code First多个FK关联到单个模型对象

时间:2012-05-21 23:49:51

标签: entity-framework ef-code-first

使用EF Code First我有一个模型对象,它具有多个与单个模型对象关联的属性:

public class Job 
{
    public int Id { get; set; }
    public int Company1Id { get; set; }
    public int Company2Id { get; set; } // References CompanyId
    public int Company3Id { get; set; } // References CompanyId
    ...

    public virtual Company Company1Info { get; set; }
    public virtual Company Company2Info { get; set; }
    public virtual Company Company3Info { get; set; }
 }

 public class Company
 { 
    public int CompanyId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
 }

JobMap类中的关系

        this.HasRequired(t => t.Company1Info)
            .WithMany()
            .HasForeignKey(d => d.Company1Id);
        this.HasRequired(t => t .Company2Info)
            .WithMany()
            .HasForeignKey(d => d.Company2Id);
        this.HasRequired(t => t.Company3Info)
            .WithMany()
            .HasForeignKey(d => d.Company3Id);

我的仓库中获取数据的方法

 public Job GetById(int id)
    {
        return _dbContext.Set<Job>()
            .Include(t => t.Company1Info)
            .Include(t => t.Company2Info)
            .Include(t => t.Company3Info)
            .First(x => x.Id == id);
    }

当我运行应用程序时,Company2Info和Company3Info为空。我尝试在上下文中为每个公司设置一个新的DbSet实例,但我得到了Unsupported Exception

谢谢!

更新:以下是同一问题的答案,但这对我不起作用Entity Framework Code First - two Foreign Keys from same table

1 个答案:

答案 0 :(得分:0)

<强>解决方案:

我在问题中的设置和链接中的解决方案是正确的。我创建实例的对象模型由于不存在的密钥而为null - 换句话说,我试图引用的公司的Id不存在。

我做的唯一更改是添加WillCascadeOnDelete方法并将其设置为false,因为默认值为true - 请注意我在JobMap类中使用Fluent API而不是Context模型构建器。

JobMap类中的关系

    this.HasRequired(t => t.Company1Info)
        .WithMany()
        .HasForeignKey(d => d.Company1Id)
        .WillCascadeOnDelete(false);
    this.HasRequired(t => t .Company2Info)
        .WithMany()
        .HasForeignKey(d => d.Company2Id)
        .WillCascadeOnDelete(false);
    this.HasRequired(t => t.Company3Info)
        .WithMany()
        .HasForeignKey(d => d.Company3Id)
        .WillCascadeOnDelete(false);

HTH