从JSON对象创建实体框架模型

时间:2018-09-05 06:21:47

标签: entity-framework

使用以下JSON对象,我想在EF中创建模型,它们的导航属性也需要model.Builder实体

还需要使用下面指定的json并使用迁移创建数据库表的一对多关系信息。

[{

"Title": "AC",
"IconClass": "ac",
"Departments": "Housekeeping,Maintenance",
"Status": "NotInOrder",
"Parts": [{
    "Title": "Power",
    "IconClass": "power",
    "Departments": "Housekeeping,Maintenance",
    "Status": "NotInOrder",
    "DependentUpon": "",
    "Id": null
}, {
    "Title": "Remote",
    "IconClass": "remote",
    "Departments": "Housekeeping,Maintenance",
    "Status": "CleanedMaintained",
    "DependentUpon": "Power",
    "Id": null
}, {
    "Title": "Cooling",
    "IconClass": "cooling",
    "Departments": "Housekeeping,Maintenance",
    "Status": "CleanedMaintained",
    "DependentUpon": "Remote",
    "Id": null
}],
},
{

"Title": "TV",
"IconClass": "tv",
"Departments": "Housekeeping,Maintenance",
"Status": "CleanedMaintained",
"Parts": [{
    "Title": "Power",
    "IconClass": "power",
    "Departments": "Housekeeping,Maintenance",
    "Status": "CleanedMaintained",
    "DependentUpon": "",
    "Id": null
}, 
{
    "Title": "TV - Remote",

    "IconClass": "remote",
    "Departments": "Housekeeping,Maintenance",
    "Status": "CleanedMaintained",
    "DependentUpon": "Power",
    "Id": null
}]
]

1 个答案:

答案 0 :(得分:1)

根据您的JSON对象,您的Entity Framework模型类应如下所示:

public class Product
{
    [Key]
    public int ProductId {get; set;}
    public string Title { get; set; }
    public string IconClass { get; set; }
    public string Departments { get; set; }
    public string Status { get; set; }

    public ICollection<Part> Parts { get; set; }
}

public class Part
{
    [Key]
    public string Id { get; set; }
    [ForeignKey("Product")]
    public int ProductId {get; set;}
    public string Title { get; set; }
    public string IconClass { get; set; }
    public string Departments { get; set; }
    public string Status { get; set; }
    public string DependentUpon { get; set; }

    public Product Product {get; set;}

}

然后是DbContext:

public class YourDbContext : DbContext
{
    public YourDbContext () : base("name=DefaultConnection")
    {
    }

    public static YourDbContext  Create()
    {
        return new YourDbContext ();
    }

    public DbSet<Product> Products { get; set; }

    public DbSet<Part> Parts { get; set; }

}