DeadlyDan
DeadlyDan

Reputation: 699

ASP.Net Dynamic Data - Show Columns from Two Tables as Single Entity

I have created a new C# ASP.NET Dynamic Data Website which provides CRUD functionality for all the table entities in my EDMX file.

The following tables are in the file :

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


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

Where CustomerId is a PK in Customers and a FK in Documents. However When the Dynamic Web App displays all the rows in Documents I want to display the following columns in the GridView:

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

Its important when a user sees the list of all Documents that they can also see which CustomerName is associated with each Document. I do not want to edit the CustomerName from the Documents list. Its just to help with viewing. How can I see CustomerName from Document GridView in Dynamic Data Web App?

I used Code First From Database with VS2012, here is the entities generated from 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; }
    }
 }

And the Documents Entity is:

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; }         
    }
}

Upvotes: 0

Views: 321

Answers (1)

DavidG
DavidG

Reputation: 118957

You can create an anonymous type for the data:

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

Alternatively, it is likely preferable to put this into a concrete class:

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; }
}

And get the data with a slight modification:

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

Upvotes: 1

Related Questions