2011-10-20 47 views
1

我一直負責移植舊的應用程序來MVC 3,想先用EF的代碼複製其現有的數據庫模式。當前的代碼庫中散佈着硬編碼的SQL命令,因此我提出的模型必須與當前系統期望的「兼容」。我知道我可以使用EF的Database First來做到這一點,但現有的模式非常簡單,我認爲沒有理由不先使用代碼,因爲我們希望有一個堅實的基礎來構建,因爲我們正在從舊的硬編碼數據庫遷移出去互動。一對一的映射

我需要的波蘇斯樣子:

public class Owner 
{ 
    [Key] 
    public Guid Owner_Id { get; set; } 

    // Properties 
    public string ContactName { get; set; } 
    public string PhoneNumber { get; set; } 
    public string Email { get; set; } 

    // Navigational properties 
    public virtual ICollection<Plant> Plants { get; set; } 
} 

public class Plant 
{ 
    [Key] 
    public Guid Plant_Id { get; set; } 

    // Properties 
    public string Address { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Zip { get; set; } 

    // Foreign Keys 
    public Guid Owner_Id { get; set; } 

    // Navigational properties 
    public virtual Owner Owner { get; set; } 
    public virtual License License { get; set; } 
} 

public class License 
{ 
    [Key] public Guid License_Id { get; set; } 

    // Properties 
    public int Total { get; set; } 
    public int Users { get; set; } 
    public string Key { get; set; } 

    // Foreign Keys 
    public Guid Plant_Id { get; set; } 

    // Navigational properties 
    public virtual Plant Plant { get; set; } 
} 

它讓我在試圖創建的背景下,這個錯誤:

「無法確定類型「之間的關聯的主要終點許可證「和」工廠「,這個關聯的主要結局必須使用關係流暢API或數據註釋來顯式配置。」

我認識到,工廠應該有一個可爲空FK參照License_Id,並且該許可證不應該有一個Plant_Id FK。但這些都是我處理過的卡片。 EF正在嘗試做什麼?

回答

1
public class Plant 
{ 
    public Guid PlantID { get; set; } 
    public virtual License License { get; set; } 
} 

public class License 
{ 
    // No need to have a PlantID foreign key since the foreign key. 
    public Guid LicenseID { get; set; } 
    public virtual Plant Plant { get; set; } 
} 

在流暢的API(在你的上下文類):

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Plant>().HasOptional(p => p.License).WithRequired(l => l.Plant); 

唯一的降級是,你實際上定義了一個0或1。 (可以在代碼中處理,但仍然...)有關一對一關係的更多信息,請查看Entity Framework Code First One to One Relationship

1

嘗試在許可證

// Foreign Keys 
public Guid Plant_Id { get; set; } 

// Navigational properties 
[ForeignKey("Plant_Id")] 
public virtual Plant Plant { get; set; } 

加入,讓它知道這是外鍵,同爲其它外鍵。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Plant>() 
      .HasOptional(e => e.License) 
      .WithOptionalPrincipal(e => e.Plant); 

    } 
+0

現在我收到一個新錯誤:「System.Data.Edm.EdmAssociationEnd::Multiplicity is is在'License_Plant'關係中的角色'License_Plant_Source'中無效。因爲依賴角色屬性不是關鍵屬性,所以相關角色的多重性的上界必須是「*」。不知道最後的亂碼是怎麼回事...... – Stevoman

+0

這是相反的。 – Birey

+0

仍然沒有去,回到原來的錯誤。 :( – Stevoman