【问题标题】:ASP.Net Dynamic Data - Show Columns from Two Tables as Single EntityASP.Net 动态数据 - 将两个表中的列显示为单个实体
【发布时间】:2015-01-17 05:51:50
【问题描述】:

我创建了一个新的 C# ASP.NET 动态数据网站,它为我的 EDMX 文件中的所有表实体提供 CRUD 功能。

文件中有以下表格:

Customers
-----------
CustomerId 
CustomerName


Documents
-----------
DocumentId
DocumentName
DocumentType
CustomerId 

其中 CustomerId 是客户中的 PK 和文档中的 FK。但是,当动态 Web 应用程序显示 Documents 中的所有行时,我想在 GridView 中显示以下列:

Documents
-----------
DocumentId
DocumentName
DocumentType
CustomerId 
CustomerName

当用户看到所有文档的列表时,他们还可以看到哪个 CustomerName 与每个文档相关联,这一点很重要。我不想编辑文档列表中的 CustomerName。它只是为了帮助观看。如何在 Dynamic Data Web App 中从 Document GridView 中查看 CustomerName?

我在 VS2012 中使用 Code First From Database,这是从 EF 生成的实体:

namespace DocMappings
{
    using System;
    using System.Collections.Generic;

    public partial class Customers
    {
        public Customers()
        {
            this.Documents = new HashSet<Documents >();
        }

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }


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

文档实体是:

namespace DocMappings
{
    using System;
    using System.Collections.Generic;

    public partial class Documents
    {            
        public int DocumentId { get; set; }
        public string DocumentName { get; set; }
        public int DocumentType{ get; set; }
        public int CustomerId { get; set; }


        public virtual Customers Customers { get; set; }         
    }
}

【问题讨论】:

  • 我读到不能使用复杂类型,这是我能想到的唯一方法。
  • 好吧,我们无法知道您可以/不能使用什么,因为我们甚至不知道您使用的是什么语言!您需要提供更多上下文和一些可作为帮助基础的代码。
  • 要点——我现在已经添加了实体,所以应该更清楚
  • 所以Documents 包含许多Document 对象?这很重要还是你现在不担心它们?
  • 嗨大卫,我已经删除了 ICollection,因为它不正确。谢谢

标签: asp.net entity-framework


【解决方案1】:

您可以为数据创建匿名类型:

var docs = context.Documents.SelectMany(d => new 
    {
        d.DocumentId,
        d.DocumentName,
        d.DocumentType,
        d.CustomerId,
        d.Customer.CustomerName 
    });

或者,最好将其放入一个具体的类中:

public class CustomerDocument
{
    public int DocumentId { get; set; }
    public string DocumentName { get; set; }
    public int DocumentType { get; set; }
    public int CustomerId { get; set; }
    public string CustomerName  { get; set; }
}

稍作修改即可获取数据:

List<CustomerDocument> docs = context.Documents.SelectMany(d => new CustomerDocument
    {
        d.DocumentId,
        d.DocumentName,
        d.DocumentType,
        d.CustomerId,
        d.Customer.CustomerName 
    });

【讨论】:

  • 好的,我将如何让它与动态数据一起显示?
  • 据我了解,gridivew 默认只显示表格。
猜你喜欢
  • 1970-01-01
  • 2016-06-30
  • 2022-10-02
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多