sqlite 如何将列表添加到实体数据模型?

8hhllhi2  于 2023-03-03  发布在  SQLite
关注(0)|答案(2)|浏览(101)

我已经创建了一个实体,我需要一个条目,其中列出了多个大小,即L,M,X,W,我可以稍后Map通过从我的客户端显示可用的大小。
我的数据模型:

namespace API.Entities
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long Price { get; set; }
        public string PictureUrl { get; set; }
        public string Type { get; set; }
        public string Brand { get; set; }
        public int QuantityInStock { get; set; }
    }
}

种子数据示例

new Product
                {
                    Name = "Shirt",
                    Description ="Text.",
                    Price = 20000,
                    PictureUrl = "url",
                    Brand = "Brand",
                    Type = "Shirt",
                    QuantityInStock = 10,
                },

已尝试添加“公用列表大小{ get;设置; }',然后'大小= {“L”,“M”,“XL”}',但它不起作用。

tag5nh1u

tag5nh1u1#

您需要为大小创建单独的表/实体,然后在两者之间创建关系。

namespace API.Entities
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long Price { get; set; }
        public string PictureUrl { get; set; }
        public string Type { get; set; }
        public string Brand { get; set; }
        public int QuantityInStock { get; set; }
        public List<ShirtSize> ShirtSizes { get; set; }
    }
    
    public class ShirtSize
    {
       public int Id { get; set; }
       public int ProductId { get; set; }  //This becomes the foreign key
       public string Size { get; set; }

    }
}

您也可以尝试将其作为逗号分隔的列表保存到后端,然后使用未Map的属性将其拆分为一个列表。

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long Price { get; set; }
        public string PictureUrl { get; set; }
        public string Type { get; set; }
        public string Brand { get; set; }
        public int QuantityInStock { get; set; }
        public string Sizes { get; set; }

        [NotMapped]
        public string[] ShirtSizes { 
                                     get { return Sizes.Split(','); }
                                     set { Sizes = String.Join(',', value);}
                                    }
    }
gab6jxml

gab6jxml2#

一旦你使用enum关键字指定了一个enum,这个enum就像一个类型,就像一个classstruct一样。
下面是如何使用自定义枚举实现属性:

public enum _Sizes { L, M, XL };
public _Sizes Sizes{ get; set; }

相关问题