【问题标题】:display additional data to table fields - entity framework 4向表字段显示附加数据 - 实体框架 4
【发布时间】:2011-04-21 00:56:26
【问题描述】:

我有Calls 表:

Call(id, reason_id, company_id, text)   

我有Reason 表:

Reason(id, name)  

我有Company 表:

Company(id, name)  

Calls 有一个指向 ReasonCompany 的外键

我正在使用 Entity Framework 4,我想显示一个呼叫列表,并为每个呼叫显示文本、原因名称和公司名称。

类似于内部连接。

我已将表格添加到 edmx 文件中。我怎样才能得到我需要的数据?哪个 POCO 对象将保存外部数据(公司名称和原因名称)?

【问题讨论】:

    标签: c# .net entity-framework


    【解决方案1】:

    也许你可以使用 ViewModel 的概念:

     //Create  CallViewModel contains ReasonName & CompanyName
        public class CallViewModel
        {
            public int id { get; set; }
            public string Text{ get; set; }
            public string ReasonName { get; set; }
            public string CompanyName { get; set; }
        }
    
    public List<CallViewModel> YourMethid()
    {
        using (Entities _entities = new Entities())
        {
            var result = (from s in _entities.Call.Include("Reason").Include("Company")
                          select new CallViewModel
                              {
                                  id = s.id,
                                  Text = s.Text,
                                  CompanyName = s.Company.name,
                                  ReasonName = s.Reason.name
                              }).ToList();
            return result;
        }
    }
    

    ======================== //从_entities调用表中选择所有数据

    var result = (from s in _entities.Call.Include("Reason").Include("Company") select s).ToList();

    //获取第一个数据的原因名称

    var ReasonName = 结果[0].Reason.ReasonName;

    //获取第一个数据的公司名称

    var CompanyName = 结果[0].Company.CompanyName;

    【讨论】:

    • @Maidot:我应该把这些值放在哪里?哪个 POCO 将保存附加信息?
    • Naor:你用什么样的控件来显示数据? yae POCO Entities 将持有该值,如果您使用“Include”~
    • @Naor:对不起,这是我的错,延迟加载可能不适用于“包含”
    • @Maidot:请参阅我写给 BrandonZeider 的评论。我需要尽可能少的数据。
    • @Naor:为什么不使用 Ajax 来获取您想要的信息?
    【解决方案2】:

    试试这个:

    using (YourEntities ctx = new YourEntities())
    {
        //In this example, "Reason" and "Company" are the name of
        //your navigation properties
        return ctx.Calls.Include("Reason").Include("Company").ToList();
    }
    

    这会给你一个List&lt;Call&gt;。所以每个电话都会有Call.Reason.Name 或类似的东西,具体取决于您的型号。

    【讨论】:

    • 如果我有延迟加载,是否需要包含?
    • 公司实际上有很多数据,但我只需要公司名称。此外 - 我需要将数据传递给客户端,并且我需要尽可能少的数据。
    • 实体框架不允许您指定要检索哪些列以及要跳过哪些列。延迟加载只有在它们是活动连接时才会起作用,因此您将要使用 .Include,水合对象,然后将它们传递给客户端。如果您希望它们尽可能薄,请删除延迟加载并使用 POCO 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多