2016-01-04 71 views
1

我想在一個實體中實現許多一對一或一對一的關係,但是我有問題讓它工作,然後生成遷移它。具有許多一對一或一對一關係的實體框架

public class Invoice 
{ 
    public int Id { get; set; } 
    public int? MorningExpenseId { get; set; } 
    public int? EveningExpenseId { get; set; } 
    public Expense MorningExpense { get; set; } 
    public Expense EveningExpense { get; set; } 
} 

public class Expense 
{ 
    public int Id { get; set; } 
    public int InvoiceId { get; set; } 
    public Invoice Invoice { get; set; } 
} 
modelBuilder.Entity<Invoice>() 
    .HasOptional<Expense>(p => p.MorningExpense) 
    .WithRequired(g => g.Invoice); 

modelBuilder.Entity<Invoice>() 
    .HasOptional<Expense>(p => p.EveningExpense) 
    .WithRequired(g => g.Invoice); 

但是我收到了一個錯誤Schema specified is not valid. Errors: The relationship '...' was not loaded because the type '...' is not available.。 我還與在'Expense'類像使用一次複合鍵的實驗:

public enum ExpenseType { Morning, Evening }; 
public class Expense 
{ 
    public int Id { get; set; } 
    public ExpenseType ExpenseType { get; set; } 
    public Invoice Invoice { get; set; } 
} 

但還沒有運氣得到它的工作。這應該如何使用Fluent API實現?

+0

伊夫不需要使用可空 '公衆詮釋的? MorningExpenseId {get;組; }' 'public int? EveningExpenseId {get;組; }' 而不是使用我的例子從我的git頁面 '公共虛擬列表關鍵字{get;組; }' 'public virtual ApplicationUser User {get;組; }' 這將使用虛擬關鍵字將實體鏈接到彼此 – TinMan7757

+0

我只需要評論......從數據庫的角度來看,無論身處何處都使用「Id」,這是不好的。我鼓勵你用名稱:ExpenseId,InvoiceId等來命名錶中的Id列。 – ErikE

回答

2

在實體框架中,應用類型必須與數據庫類型匹配。關係必須具有虛擬鍵功能。

你必須像這樣的代碼

public class Invoice 
{ 
    public int Id { get; set; } 
    public int MorningExpenseId { get; set; } 
    public int EveningExpenseId { get; set; } 
    public virtual Expense MorningExpense { get; set; } 
    public virtual Expense EveningExpense { get; set; } 
} 

public class Expense 
{ 
    public int Id { get; set; } 
    public int InvoiceId { get; set; } 
    public virtual Invoice Invoice { get; set; } 
} 
+0

注意到你不需要Invoice類中的MorningExpenseId和EveningExpenseId,因爲你不需要InvoiceId費用類。實體框架將處理關係中的Id。 –

+0

你是對的我不需要這兩個ID,但也請注意,它們是可空的,因爲它們是可選的。此外,虛擬關鍵字是可取的,但不是強制性的,除非你想利用延遲加載。這是我正在使用的代碼的簡化版本,所以我對這些小小的「錯別字」表示歉意。 但是,我的問題的關鍵是,我沒有得到多個一對一或一對關係的工作,得到我在我的帖子中指出的錯誤。 –