实体框架条件连接

时间:2018-09-12 08:42:12

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

我已经使用实体框架创建了MVC,但遇到了一种我不知道如何解决的情况。

我正在使用EF自动联接和关系(我的所有表模型都是由EF自动创建的)。

现在解决这个问题-我有一个客户表,其中有两个(relavent)字段-personIDemployerID。它们中只有一个包含数据,另一个将为null(客户是个人或雇主)。当我尝试在结果集中包含employer模型时,我会被抛出(没有任何消息,当我调试时,我看到内容包含数据,但employeer有时为NULL),我也不确定设计看起来如何。这是我的代码:

客户:

public partial class Customer
{
    public Customer()
    {
        Account = new HashSet<Account>();
    }

    public long Id { get; set; }
    public int? PersonId { get; set; }
    public int Type { get; set; }
    public int? EmployerId { get; set; }

    public Employer Employer { get; set; }
    public ICollection<Account> Account { get; set; }
}

雇主:

public partial class Employer
{
    public Employer()
    {
        Customer = new HashSet<Customer>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int? IdType { get; set; }

    public ICollection<Customer> Customer { get; set; }
}

人员:

public partial class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Sex { get; set; }
    public DateTime? BirthDate { get; set; }
    public int IdType { get; set; }
}

现在,当我在存储库中运行时:

 var collectionBeforePaging = _context.Customer

一切正常,但是Employer为NULL。如果我使用:

 var collectionBeforePaging = _context.Customer.Include(a => a.Employer)

然后项目失败。

我该如何加入?

2 个答案:

答案 0 :(得分:0)

请为客户定义ForeignKey

public int? EmployerId { get; set; }

[ForeignKey(nameof(EmployerId))]
public virtual Employer Employer { get; set; }

答案 1 :(得分:0)

您使用什么版本的EF?我认为您缺少这样的东西:

在雇主中:

[ForeignKey("EmployerId")]    
[InverseProperty("Customers")]
public virtual Employer Employer { get; set; }

public int? EmployerId { get; set; }

在客户中:

[InverseProperty("Employer")]
public virtual ICollection<Customer> Customers { get; set; }

也可以在Dbontext对象中完成