Entity Framework Code First primitive collections

旧时模样 提交于 2019-12-12 21:16:13

问题


Given the following simple scenario, what is the best/simpleset way to have a simple collection of primitives persisted?

public class Subscriber
{
    public int Id { get; set; }
    public string Email { get; set; }
    public ICollection<int> SubscribedNodeIds { get; set; }
}

If I execute the above example the SubscribedNodeIds column is ignored.


回答1:


The obvious answer is to create relationship like so:

public class Subscriber
{
    public int Id { get; set; }
    public string Email { get; set; }
    public ICollection<Subscription> Subscriptions { get; set; }
}

public class Subscription
{
    public int Id { get; set; }
    public int NodeId { get; set; }
    public Subscriber Subscriber { get; set; }
}



回答2:


Creating a new entity and relation is a laborious work. Instead we can do the following simple 2 steps

Annotate the collection field with [NotMapped] so that it is not added to database

Add a string property and use Json serializer to convert the primitive collection to string.

The code is given below

public class Subscriber
{
    public int Id { get; set; }
    public string Email { get; set; }
    [NotMapped]`enter code here`
    public ICollection<int> SubscribedNodeIds { get; set; }
    public string SubscribedNodeIdsString 
    {
        get => JsonConvert.SerializeObject(SubscribedNodeIds);
        set
        {
            if (value != null)
            {
                SubscribedNodeIds = JsonConvert.DeserializeObject<List<Int>>(value);                    
            }
        }
    }
}


来源:https://stackoverflow.com/questions/7236630/entity-framework-code-first-primitive-collections

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