EF Code First not generating table for ICollection

前端 未结 4 673
旧时难觅i
旧时难觅i 2020-12-07 01:28

I would like the below ICollection property in one of my data classes (let\'s call it \"Foo\")

public class Foo
{
    [Key]
    public int FooId { get; set;          


        
4条回答
  •  猫巷女王i
    2020-12-07 01:47

    I know this is not best practice in all cases, but I think there are cases where storing a comma seperated list of your array in a column is a good way to solve this problem.

    Conditions include:

    • The list is not going to be long
    • You don't need to search for entities based on the values in that list

    It could also be a good idea if one entity has multiple string lists in it that would create lots of joins.

    In those cases I would solve it by having two properties for the list. One being the comma seperated list used by EF and the other a list that you can use when accessing the items in the list like this:

    [NotMapped]
    public List AllowedBars { get; set; }
    
    /// 
    /// Comma seperated list of AllowedBars
    /// 
    public String AllowedBarsList
    {
        get { return String.Join(",", AllowedBars); }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                AllowedBars.Clear();
            }
            else
            {
                AllowedBars = value.Split(',').ToList();
            }
        }
    }
    

    You need to initialise AllowedBars to be an empty list in the constructor.

    You don't need to use the [NotMapped] attribute as this collection won't be used anyway, but I think it makes the intent clearer.

提交回复
热议问题