如何在MVC 5中连接两个表的字段?

时间:2014-08-06 14:24:43

标签: c# entity-framework

我有两个模型,我将通过迁移和数据库更新来创建表。我的第一个模型名为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字段添加到我的Business模型中,但Category和Subcategory字段的值应该是Service表的Category和Subcategory的值中的值之一。

简单地说,我想连接这两个字段。我怎样才能实现它?我应该只在Business模型中放置一个Service属性吗?

2 个答案:

答案 0 :(得分:0)

为"类别"打破一个单独的实体。然后使用外键:

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的关系。

答案 1 :(得分:0)

您需要将数据库中断以存储类别的查找表和子类别的查找表。

然后你可以创建:

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; }
}

并将您的商务课程更改为:

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
}