Entity Framework Code First and Collections of Primitive Types

安稳与你 提交于 2019-12-01 15:32:51

Promoting simple type to entity is one option. If you want to use that new primitive type entity in more relations it is better to completely remove navigation properties from that entity and use independent association (no FK properties).

public class StringEntity
{
    public int Id { get; set; }
    public string Text { get; set; }
}

and mapping:

modelBuilder.Entity<Foo1>().HasMany(f => f.Strings).WithOptional();
modelBuilder.Entity<Foo2>().HasMany(f => f.Strings).WithOptional();

In database you will get new nullable FK per related principal - there is no way to avoid it except create special StringEntity class per principal (don't use inheritance for that because it affects performance).

There is an alternative:

public class StringEntity
{
    public int Id { get; set; }
    public List<string> Strings { get; private set; }

    public string Text 
    {
        get
        {
            return String.Join(";", Strings);
        }

        set
        {
            Strings = value.Split(";").ToList();
        }
    }   
}

In this case you don't need related entity type (and additional table) but your entity is polluted with additional property Text which is only for persistence.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!