开发者

Entity Framework - Code First not generating associated collections in the Database

开发者 https://www.devze.com 2023-01-30 01:28 出处:网络
I\'m using CTP5 of the code first. Take the following simple class and associated DbContext public class Test

I'm using CTP5 of the code first. Take the following simple class and associated DbContext

public class Test
{
    public Test()
    {
        Keywords = new Collection<string>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Keywords { get; set; }
}

public class TestDbContext : DbContext
{
    public Te开发者_如何学PythonstDbContext()
    {
        Database.Delete();
        Database.CreateIfNotExists();
    }

    public DbSet<Test> Tests { get; set; }

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {       
        base.OnModelCreating(modelBuilder);
    }
}

The type 'System.Collections.Generic.ICollection' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration .Property(System.Linq.Expressions.Expression>)'

Any ideas how to create the necessary table relationships between test class and the keywords property?


Add class Keyword and change ICollection<string> Keywords {get; set;} to ICollection<Keyword> Keywords {get; set;}

public class Keyword
{
    public string Data {get;set;}
}

and code model creating like this:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Keyword>()
        .HasKey(x => x.Data);
    base.OnModelCreating(builder);
}

Just imagine, that you have 2 collections 1 - Keywords, 2 - Tags. Your realization would map it to same table, because in ORM mapping type defines entity. And both Keyword and Tag are of type string. So to split this entities you should split types.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号