簡體   English   中英

實體框架條件連接

[英]Entity Framework Conditional join

我已經使用實體框架創建了MVC,但遇到了一種我不知道如何解決的情況。

我正在使用EF自動聯接和關系(我的所有表模型都是由EF自動創建的)。

現在的問題-我有客戶的表,其中有兩個(relavent)領域- personIDemployerID 它們中只有一個包含數據,另一個將為null(客戶是個人或雇主)。 當我嘗試將employer模型包括在結果集中時,我會被拋出(沒有任何消息,當我調試時,我看到內容包含數據,但employee有時為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)

然后項目失敗了。

我該如何加入?

請為客戶定義ForeignKey

public int? EmployerId { get; set; }

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM