【发布时间】:2013-09-22 08:37:25
【问题描述】:
我正在尝试为我的 Web 应用程序适当地构建我的数据库。我不确定处理键和关系的正确方法。基本上..
我的项目包含一个产品
其中可以包含许多报告,但是,同一个报告可以不与多个产品相关。
我有用户,他们可能有很多报告可供他们使用。无论报告的父产品如何。
到目前为止我的结构
public class Product
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Report
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual Product Product { get; set; }
}
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Report> Reports { get; set; }
}
还有Seed
protected override void Seed(Insight.Data.InsightDb context)
{
context.Products.AddOrUpdate(p => p.ProductID,
new Product { ProductName = "Product 1" },
new Product { ProductName = "Product 2" }
);
context.Reports.AddOrUpdate(p => p.ReportID,
new Report { ReportName = "Report A", ProductID = 1, },
new Report { ReportName = "Report B", ProductID = 1, },
new Report { ReportName = "Report C", ProductID = 1, },
new Report { ReportName = "Report D", ProductID = 2, },
new Report { ReportName = "Report E", ProductID = 2, }
);
context.Users.AddOrUpdate(u => u.UserID,
new User { FirstName = "Frank", LastName = "Reynolds", },
new User { FirstName = "Dee", LastName = "Reyonolds", }
);
}
我不确定如何正确地将报告分配给用户,甚至不知道我是否走在正确的轨道上。另外,有没有比使用 int 作为键更好的做法?
【问题讨论】:
-
查看我刚刚对您的模型所做的编辑。也许这会有所帮助。如果我的理解是正确的..您想要一个拥有与其相关联的报告列表的用户,并且您希望每个报告中都有一个独特的产品?
-
谢谢。一旦我在 SQL Server 中并手动填充和查询表,实体模型就会正确排列。您能否提供一个示例以在 Seed() 内的 C# 代码中适当地填充它们?
标签: c# asp.net entity-framework database-design ef-code-first