【问题标题】:Entity Framework Conditional join实体框架条件连接
【发布时间】:2018-09-12 19:29:48
【问题描述】:

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

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

现在的问题 - 我有一个客户表,其中有两个(相关)字段 - personIDemployerID 。其中只有一个包含数据,另一个将为空(客户要么是个人,要么是雇主)。当我尝试在结果集中包含 employer 模型时,我被抛出(没有任何消息,当我调试时我看到内容有数据但员工有时为 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)

那么项目就失败了。

我怎样才能使这个加入?

【问题讨论】:

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


    【解决方案1】:

    请为客户定义外键

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

    【讨论】:

    • 您可以尝试将virtual 添加到对象和列表对象的所有属性中吗?你在使用延迟加载吗?
    • 我可以试试.. 但是为什么它们应该是虚拟的?
    • 使用 Entity Framework,需要使用“virtual”键来启用 D​​bContext 对象内的代理创建和延迟加载
    • 这真的很奇怪,因为没有virtualincludeEmployer 将永远为空
    【解决方案2】:

    您使用什么版本的 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对象中完成

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2015-02-22
      • 2011-04-08
      相关资源
      最近更新 更多