2013-01-12 50 views
10

我似乎無法在流利的API中找到一對多的關係語法。流利的API - 一對多

作爲一個例子我有兩個表如下

用戶

Id 
Name 

UserHistory

Id 
UserId 
Date 

在類我有以下

public class User 
{ 
    public int Id { get; set; } 
    public virtual ICollection<UserHistory> Histories { get; set; } 
} 

public class UserHistory 
{ 
    public int Id { get; set; } 
    public int UserId { get; set; } 
    public DateTime Date { get; set; } 
} 

我試過以下,但我不確定它是否真的正確。

modelBuilder.Entity<User>() 
     .HasRequired(w => w.Histories) 
     .WithMany(); 

modelBuilder.Entity<User>() 
     .HasMany(f => f.Histories) 
     .WithOptional() 
     .HasForeignKey(f => f.UserId); 

什麼是一對多關係的正確語法?

從技術上講,我可以通過添加一個新表將其分解爲多對多,但我不想引入另一個表。

回答

24

在模型中User實體有許多Histories每個歷史有需要User和關係具有一個外鍵稱爲UserId

modelBuilder.Entity<User>() 
    .HasMany(u => u.Histories) 
    .WithRequired() 
    .HasForeignKey(h => h.UserId); 

(的關係必須是必需的(不是可選的),因爲外鍵屬性UserId不是nullab )

+1

如果UserHistory UserId爲空,那麼它會是WithOptional()? – fes

+1

@fes:是的,沒錯。 – Slauma