Linq to Entities使用连接和通用列表

时间:2013-08-22 19:03:43

标签: linq list generics

我正在使用Linq,刚开始使用它。 当我使用单个表时,我的gridview正在填充,但现在我正在尝试从客户端信息表中加入客户端名字。

错误是Event_Setup不包含ClientFirstName的定义。所以它检查Event_Setup表而不是Client_Info。

public List<EventData> GetDetails()
    {
        using (EMSEntities db = new EMSEntities())
        {
            var context = from events in db.Event_Setup
                          join clients in db.Client_Info on events.ClientId equals clients.ClientId 
                        select events;

            List<EventData> newEvent = new List<EventData>();

            foreach (var e in context)
            {
                EventData test = new EventData();

                test.Event_Title = e.EventTitle;

//Error on e.ClientFirstName, Event Setup does not contain Definition
 (located in Client_Info table not Event Setup)
                test.Name = e.ClientFirstName;
                test.Start_Date = e.EventDateFrom;
                test.End_Date = e.EventDateFrom;



               newEvent.Add(test);                
            }
            return newEvent;
         }         
    }

DAL

public class EventData
{        
        public string Event_Title { get; set; }
        public string Name { get; set; }
        public DateTime? Start_Date { get; set; }
        public DateTime? End_Date { get; set; }            
}

2 个答案:

答案 0 :(得分:1)

此代码未对加入的clients数据执行任何操作。您可以看到它只是选择events

var context = from events in db.Event_Setup
              join clients in db.Client_Info on events.ClientId equals clients.ClientId 
              select events;

一旦你退出LINQ语句,clients就消失了。它不会为您合并任何数据。您需要进行投影,如下所示:

var context = from events in db.Event_Setup
              join clients in db.Client_Info on events.ClientId equals clients.ClientId 
              select new EventData
              {
                  Event_Title = events.EventTitle,
                  Name = clients.ClientFirstName,
                  Start_Date = events.EventDateFrom,
                  End_Date = events.EventDateFrom
              };

答案 1 :(得分:0)

感谢您对Cory的感谢,对于任何查看此问题的人来说,这是列表的内容

foreach (var e in context)
            {
                EventData test = new EventData();

                test.Event_Title = e.Event_Title;
                test.Name = e.Name;
                test.Start_Date = e.Start_Date;
                test.End_Date = e.End_Date;           

                newEvent.Add(test);                
            }
            return newEvent;