0

我創建了一個模型實體框架與長列名創建數據庫

public class Moo 
{ 
    public Int32 MooId { get; set; } 
    public string Description { get; set; } 
    public City CityIdFrom { get; set; } 
    public Int32 Weight { get; set; } 
} 

public class City 
{ 
    public Int32 CityId { get; set; } 
    public string Name { get; set; } 
} 

和我的Global.asax.cs

寫道

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     System.Data.Entity.Database.SetInitializer(
      new System.Data.Entity.DropCreateDatabaseAlways<DbConnection>()); 
     ... 

高於預期

簡而言之 - 我follo在here的教程。

不過,我得到一個數據庫表哞的列創建如下:

[MooId] 
    ,[Description] 
    ,[Weight] 
    ,[CityIdFrom_CityId] 

但是,因爲它是在本教程中,我希望這一下爲:

[MooId] 
    ,[Description] 
    ,[Weight] 
    ,[CityIdFrom] 

是什麼生成器添加不必要的原因_CityId? (所有關係表中的列都一樣)我很確定必須有一個設置,但我覺得很難說出我的問題。

回答

1

您在Moo模型中沒有明確聲明FK列。

CityIdFrom屬性是City類型的導航屬性,而不是Int32類型的FK列。

因此,您在數據庫中看到的列是由EF自動爲您創建的。

如果你想命名此列,你必須將它添加到您的模型:

public class Moo 
{ 
    public Int32 MooId { get; set; } 
    public string Description { get; set; } 

    public Int32 CityFromId { get; set; } 
    public City CityFrom { get; set; } 

    public Int32 Weight { get; set; } 
} 

注:列名按照慣例,所以EF可以找出有什麼什麼去。
所以CityFromIdCityFrom導航屬性的數據庫FK列,因爲它在末尾與Id具有相同的名稱。

0

它創建了City.CityId的外鍵,因此額外的_CityId。您需要添加屬性[Column("CityIdFrom")]以告訴框架您希望它使用非默認值。

+0

我已經添加了'System.ComponentModel.DataAnnotations.Schema.Column(「Aaa」)] public City CityIdFrom {get;組; }'但它沒有改變任何東西:(我可能只是盲目的,我也在執行前刪除了表,所以我確信它重新創建表。 –