我如何在MVC 5连接两个表的字段
本文关键字:两个 字段 MVC 连接 | 更新日期: 2023-09-27 18:16:36
我有两个模型,我将通过迁移和数据库更新为它们创建表。我的第一个模型名为Service,它由以下字段组成:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public int Count { get; set; }
}
我的第二个模型叫做Business,它有以下字段:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}
关键是我想将Category和Subcategory字段添加到我的业务模型中,但是Category和Subcategory字段的值应该是Service表中Category和Subcategory的值中的一个。
简单地说,我想连接这两个字段。我怎样才能实现它?我应该把Service属性放在业务模型中吗?
为"Category"划分一个单独的实体,然后使用外键:
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Service
{
...
public virtual Category Category { get; set; }
public virtual Category Subcategory { get; set; }
}
// Do the same when adding category/subcategory fields to `Business`
如果你想确保这些类别只与Service
绑定(并且你可能有其他类型的类别或其他东西),你总是可以将实体设置为ServiceCategory
或其他东西,并且只从Service
创建与它的关系。
您需要分离您的break out您的数据库来存储查找表的类别和查找表的子类别。
然后你可以创建:
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class SubCategory {
public int SubCategoryId { get; set; }
public string Name { get; set; }
}
然后将服务类更改为:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public int CategoryId { get; set; }
public int SubcategoryId { get; set; }
public int Count { get; set; }
}
并将您的Business类更改为:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}