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