1

我有一张位置表、一张服务分配表和一张服务表。位置和服务通过服务分配联系在一起。在位置创建中,我希望能够通过复选框为其分配服务。

但我无法访问位置创建视图中的服务。

位置模型

namespace LocApp.Models
{
    public class Location
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool active { get; set; }

        public virtual ICollection<ServiceAssignment> ServiceAssignment { get; set; }
    }
}

服务模式

namespace LocApp.Models
{
    public class Service
    {
        public int id { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public bool active { get; set; }
        public string icon { get; set; }

        public virtual ICollection<ServiceAssignment> ServiceAssignment { get; set; }
    }
}

服务分配

namespace LocApp.Models
{
    public class ServiceAssignment
    {
        public int id { get; set; }
        public int locationID { get; set; }
        public int serviceID { get; set; }

        public virtual Location Location { get; set; }
        public virtual Service Service { get; set; }
    }
}

在我的上下文类中,我没有映射任何关系,因为根据我看过的文章和屏幕截图,实体框架会为我解决这些问题。

所以这里的主要问题是:

我想在位置创建视图中访问 service.name 和 id 以创建复选框,以便在保存新位置时可以将位置 id 和该服务 id 保存在数据库中。

这里的诀窍是位置和服务具有多对多的关系。

service assignment id.
Location id -> service assignment location id 
service assignment service id <- service id

以上是服务分配表的基本布局。位置 <-> 服务的所有关系都通过此表处理。

4

2 回答 2

1

如果您想要一个真正的多对多关联,您可以ServiceAssignment从模型中完全删除该类。您的课程应如下所示:

public class Location
{
    public int id { get; set; }
    public string name { get; set; }
    public bool active { get; set; }

    public virtual ICollection<Service> Services { get; set; }
}

public class Service
{
    public int id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public bool active { get; set; }
    public string icon { get; set; }

    public virtual ICollection<Location> Locations { get; set; }
}

EF 将在数据库中创建一个联结表,并在后台使用它来解析关联。您不能直接将记录添加到此表,但您可以通过将Add()现有服务添加到Location.Services.

编辑

鉴于数据模型的约束,您可以做的是将类模型保持原样并像这样查询服务:

db.Locations.Where(loc => loc.Id == locId)
    .SelectMany(loc => loc.ServiceAssignments)
    .Select(sa => sa.Service)

您可以通过创建ServiceAssignments 并将它们添加到Location.ServiceAssignments.

它可能感觉不如直接多对多关联优雅,但根据我的经验,客户迟早会需要有关关联本身的更详细信息(例如,添加服务的日期)。发生这种情况时,您会很高兴有可用的显式类。

于 2013-04-15T18:25:42.853 回答
0

这个想法是使用tuple<>它允许我将多个模型传递给视图,然后通过model.item1.whateveritem1 作为第一个项目来访问它们。

于 2013-04-15T19:12:19.913 回答