不相关的实体

时间:2013-12-02 17:08:09

标签: c# asp.net-mvc entity-framework viewmodel

我有一份通知列表......

IList<notification> notifications = db.notification.ToList();

每个通知都有一个与业务实体相关的业务ID,但没有FK关系。

我需要显示通知以及每个...的商业名称。

  • 通知1业务
  • 通知2业务
  • 通知3业务
  • 通知4业务b
  • 通知5 business c

我使用viewmodel做了类似的事情

public person person {get; set;}
public IList<notification> notifications {get; set;}

但是我能够在viewmodel中填写通知,因为我有一个人ID,我可以抓取那个有人格的通知。

在这种情况下,我没有一个通知ID来抓住商家的通知列表......

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以加入2个列表。我在飞行中在linqpad上一起划了这个。它很可能不会代表您的模型1到1,因此您需要对其进行调整。由于您有一个通知列表,我假设您还有一个业务列表并创建了一个类似的模型。最重要的部分是:

//nList = List of Notifications | bList = List of businesses
var JoinedBusiness = from not in nList
                     join busi in bList
                     on not.BusinessId equals busi.Id 
                     select new { Notification = not.Name, Business = busi.Name };

如果您需要强类型实体而不是匿名对象,则可能需要从中创建ViewModel。

这是完整的代码,因此您可以重现它(只需将其粘贴到linqpad中):

void Main()
{
    List<Business> bList = new List<Business>()
    {
        new Business(1, "Business1"),
        new Business(2, "Business2"),
        new Business(3, "Business3"),
        new Business(4, "Business4"),
        new Business(5, "Business5"),
    };

    var nList = new List<Notification>()
    {
      new Notification(1, "Notification1", 1),
      new Notification(2, "Notification2", 1),
      new Notification(3, "Notification3", 3),
      new Notification(4, "Notification4", 2),
      new Notification(5, "Notification5", 2),
      new Notification(6, "Notification6", 2),
    };

    var JoinedBusiness = from not in nList
                         join busi in bList
                         on not.BusinessId equals busi.Id 
                         select new { Notification = not.Name, Business = busi.Name };

    JoinedBusiness.Dump();

}
public class Notification
{
    public Notification(int id, string name, int businessid)
    {
     this.Id = id; this.Name = name; this.BusinessId = businessid;
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public int BusinessId { get; set; }
}

public class Business
{
    public Business(int id, string name)
    {
      this.Id = id;
      this.Name = name;
    }
    public int Id { get; set; }
    public string Name { get; set; }
}

//编辑:如果您需要强类型,则需要一个viewmodel:

public class BusiNotVM
{
    public Notification Notifications { get; set; }
    public Business Businesss { get; set; }
}

更改您的查询以返回新的ViewModel:

var JoinedBusiness = from not in nList
                     join busi in bList
                     on not.BusinessId equals busi.Id 
                     select  new BusiNotVM 
                     { 
                       Businesss = busi,
                       Notifications = not
                     };

这为您提供以下输出: 每条水平线代表连接的entites;读:ID匹配。只需使用model.Business.Namemodel.Notifications.Name在您的视图中对其进行迭代 请记住,还要将视图所期望的模型更改为viewmodel: @model Namespace.Folder.BusiNotVM - 玩得开心。

enter image description here