当代码首次尝试生成代码时,我发现错误,它无法确定关联的主要结束

时间:2017-04-26 16:32:30

标签: c# entity-framework ef-code-first

在EF Codefirst中,我的项目中有一个中间表(Model),如`:

public class ClientDriverLoad
{
    public ClientDriverLoad()
    {
        DateTime = DateTime.Now.Date;
    }
    public int Id { get; set; }
    public virtual Client Client { get; set; }
    public DateTime DateTime { get; set; }
    public virtual List<DriverLoad> DriverLoads { get; set; }
    public virtual User User { get; set; }
}

和源自它的父客户的客户:

public class Client:Person
{
    public virtual List<ClientDriverPayment> ClientPayments { get; set; }
    public virtual List<ClientDriverLoad> ClientDriverLoad { get; set; }
}

和DriverLoad模型是这样的:

 public class DriverLoad
{
    public int Id { get; set; }
    public virtual Driver Driver { get; set; }
    public virtual Load Load { get; set; }
    public string StartPoint { get; set; }
    public string Destination { get; set; }
    public long price { get; set; }
    public virtual ClientDriverLoad ClientDriverLoad { get; set; }
}

和clientDriverPayment像这样:

public class ClientDriverPayment
{
    public ClientDriverPayment() {
        DateTime = DateTime.Now.Date;
    }
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
    public virtual Client Client { get; set; }
    public virtual Driver Driver { get; set; }
    public virtual Payment Payment { get; set; }
    public virtual User User { get; set; }
}

如果搜索了很多并且认为我应该使用Fluent Api或者我应该如何确定我应该使用哪种关系?任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

请在DbContext类中使用这些代码

protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Entity<ClientDriverLoad>().HasMany(m => m.DriverLoads).WithRequired(m => m.ClientDriverLoad);
        mb.Entity<ClientDriverPayment>().HasRequired(m => m.Client).WithMany(m => m.ClientPayments);
}