0

我剛接觸代碼第一範式,請耐心等待。我無法從我的實體類中獲取在我的數據庫上創建的基元或自定義類的集合/列表/數組。所以,結果,我無法正確種子。沒有錯誤,只需獲取除我的集合以外的每個屬性的實體表。我使用EF5,VS2010,MVC4和SqlExpress。我究竟做錯了什麼?實體框架5:使用代碼優先創建集合

我的實體類:

public class MyEntity 
{  
    public int MyEntityID { get; set; } // GOOD 
    public string Property1 { get; set; } // GOOD 
    public bool Property2 { get; set; } // GOOD 
    public IList<CustomClass> CustomClassList { get; set; } //BAD, NOT CREATED ON DB 
    public CustomClass[] CustomClassArray { get; set; } //BAD, NOT CREATED ON DB 
} 

我的自定義類:

[ComplexType] 
public class CustomClass 
{ 
    public string Title { get; set; } 
} 

我的配置/遷移類

public class Configuration : DbMigrationsConfiguration<MyContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
     AutomaticMigrationDataLossAllowed = true; 
    } 

    protected override void Seed(MyContext context) 
    { 
     context.MyEntity.AddOrUpdate(x => x.MyEntityID, 
      new MyEntity() 
      { 
       Property1 = "abc", 
       Property2 = "xyz", 
       CustomClassList = new List<CustomClass> {new CustomClass{Title="Help"}} 
      } 
     context.SaveChanges();  
    } 
} 

我的Global.asax.cs的Application_Start()方法

protected void Application_Start() 
{ 
    WebApiConfig.Register(GlobalConfiguration.Configuration); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    BundleConfig.RegisterBundles(BundleTable.Bundles); 
    AuthConfig.RegisterAuth(); 
    SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>()); 
} 

當我嘗試創建一個新的數據庫,我得到了相同的結果:

<!--NO LUCK--> 
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS2;Initial Catalog=TESTDB_2;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> 
<!--NO LUCK--> 
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS2;Initial Catalog=TESTDB_3;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> 
+0

我不能幫助遷移,但集合應聲明爲ICollection <>例如'公衆ICollection CustomClassList {get;組; }' – qujck 2013-03-08 16:27:32

回答

2

實體Framwork不支持的原始集合或複雜的類型。如果你想要一個集合,它必須是一個實體集合(即它們需要有關鍵屬性)。如果你有一個實體集合,它將在最簡單的情況下被建模爲一個單獨的表格,並根據需要創建適當的外鍵(取決於關係的基數)。 在你的情況下,CustomClass被忽略,因爲它不是一個實體,並且在集合中使用(由於它不是實體類型的集合,所以它也被忽略)。 CustomClassArray會被忽略,因爲根本不支持數組,因爲如果不重新分配數組,則無法添加/刪除項目。

+0

感謝您的迴應。我看過Julie Lerman的文章,她有一個ComplexTypes集合 - http://msdn.microsoft.com/en-us/data/jj591583.aspx。也許我誤解了她? – 2013-03-08 17:07:49

+0

這些是實體而不是複雜的類型。有關更多詳細信息,請參閱http://msdn.microsoft.com/en-us/library/ee382831.aspx。複雜類型是(原始或複雜)屬性的集合(規範示例是Address複雜類型) - 您可以在實體上創建複雜類型的屬性以對屬性進行分組,但它們將在表中建模爲列(想想:展平) 。他們不能擁有關鍵屬性,並且不能擁有複雜類型的集合(否則,如何在數據庫中對此進行建模,因爲這只是組合屬性的一種手段?)。 – Pawel 2013-03-08 17:44:59

+0

很好的解釋。那麼,爲什麼我的例子不適用於複雜類型的世界呢?它看起來應該。我在我的示例中添加了一個鍵,它在MyEntity表中創建了另一個表,但沒有字段(foriegn鍵?)。此外,新表不播種。有任何想法嗎? – 2013-03-08 18:17:41