代码之家  ›  专栏  ›  技术社区  ›  user8270367

如何在ASP中使用JSON为数据库种子。净MVC

  •  0
  • user8270367  · 技术社区  · 7 年前

    因此,我有一个json文件,其中包含以下值: My JSON

    我必须使用ASP为其创建MSSQL数据库。NET MVC和实体框架。我的问题将分为两部分。

    1. 如何使用此JSON为数据库种子?
    2. 我的模型应该是什么样的?我对规格和图像部分特别好奇。

    种子法

            using (StreamReader jsonData = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Resources/products.json")))
            {
                List<Product> products = JsonConvert.DeserializeObject<List<Product>>(jsonData.ReadToEnd());
                products.ForEach(s => context.Products.AddOrUpdate(s));
                context.SaveChanges();
            }
    

    [编辑] 我的型号:

        public class Product
    {
        public int id { get; set; }
    
        public string name { get; set; }
    
        public double price { get; set; }
    
        public string specsmanufacturer { get; set; }
    
        public int specsstorage { get; set; }
    
        public string specsos { get; set; }
    
        public int specscamera { get; set; }
    
        public string imagesmall { get; set; }
    
        public string imagelarge { get; set; }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Wurd    7 年前

    您可以展平模型(1个class 1表)或将实体存储在各自的表(3个class 3表)中。

    编辑:平面类模型。

    public class Thingy
    {
       [Key]
       public int ID{get;set;}
       public string Name{get;set;}
       public decimal Price{get;set;}
       public string SpecsManufacturer{get;set;}
       public int SpecsStorage{get;set;}
       public string SpecsOS{get;set;}
       //etc
    }
    

    如果您首先使用代码,并且 Configuration.cs 在Migrations文件夹中,可以覆盖种子方法:

    protected override void Seed(DataContext context)
    {
       //Populate using whatever method you want.
    }
    

    每次运行命令时,Seed方法都会运行 update-database 针对您的数据库。