开发者

Entity Framework Code First primitive collections

开发者 https://www.devze.com 2023-03-31 19:40 出处:网络
Given the following simple scenario, what is the best/simpleset way 开发者_如何学JAVAto have a simple collection of primitives persisted?

Given the following simple scenario, what is the best/simpleset way 开发者_如何学JAVAto 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.


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; }
}


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);                    
            }
        }
    }
}
0

精彩评论

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