Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone. This is my Entity, which is stored in database:
public class Rule
{
    [Key]
    public int ruleId { get; set; }
    public string name { get; set; }
    public int[] categoryIds { get; set; }
}


I have a converters for it like this:
public class ArrayConverter : ValueConverter<int[], string>
{
    public ArrayConverter()
        : base(x => string.Join(";", x), x => x.Split(";", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray())
    {
    }
}

public class ArrayComparer : ValueComparer<int[]>
{
    public ArrayComparer()
        : base((c1, c2) => c1.SequenceEqual(c2), c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), c => c.ToArray())
    {
    }
}


Converters are applied like this:

modelBuilder.Entity<Rule>(builder =>
   {
       builder.Property(x => x.categoryIds).HasConversion(new ArrayConverter());
       builder.Property(x => x.categoryIds).Metadata.SetValueComparer(new ArrayComparer());
   });


What I have tried:

And this works OK, on client side. I need somehow to utilize this property (
int[] categoryIds
) on server side instead. It is stored in a string column like this: 1;2;3
What is the best way I can achieve it using linq to sql?
I have tried EF.Property<string>(p, "categoryIds").Contains("1") but it fails with some error that ef.property is not used correctly. I need to run it on server side.
categoryIds are not tied to Rule object, they are system wide entities, used by all of other entities, so I cannot do this:
public ICollection<Category> categories {get;set;}
because category would need to have relation to Rule, and it cannot have such.
Posted
Updated 14-Nov-20 22:06pm

1 solution

If you need a "string" to act like a "list", just add another Getter; EF / LINQ doesn't care.
C#
public string Categories {get;set;} = "1;2;3";
public ICollection<string> CatList {get{return this.Categories.Split(';').ToList();}}
 
Share this answer
 
Comments
Richard Deeming 16-Nov-20 4:20am    
No need for the .ToList() call there; the array returned by Split already implements ICollection<string>. :)
csrss 17-Nov-20 4:10am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900