Pergunta

I have the following tables:- enter image description here

But how I can create a view model class inside my asp.net mvc4 web application, so that if I pass the AccountDefinition.OrgID I can retrieve the following:-

• accountDefinition

• SDOrganization

• SDOrgPostalAddr

• AaaPostalAddress

I have created the following CustomerDetails ViewModel

public class CustomerDetails
    {
        public AccountDefinition AccountDefinition {get; set;}
        public SDOrganization SDOrganization {get; set;}

        public virtual ICollection<AaaPostalAddress> AaaPostalAddress { get; set; }
 public virtual ICollection< SDOrgPostalAddr> AaaPostalAddress { get;set; }

    }

I have the following Repository method, which should populate the CustomerDetails based on the ORG_ID:-

public   CustomerDetails GetCustomer(int ORG_id) {

CustomerDetails cd = new CustomerDetails();
var cd = from SDorg in cd.AccountDefinition // here I will b populating the CustomerDetials
        }

My second question , as I have a database experience, I would do a stored procedure that join the the tables together then return the result back !!!, but as I am using the entity framework so I got confused on how to do so?

BR

Foi útil?

Solução

If you have created an entity framework model from your database schema you should have:

  • An AccountDefinition class with an AccountDefinition.SDOrganization reference navigation property because the relationship between the two is apparently one-to-one

  • A SDOrganization.AaaPostAddresses collection navigation property because the relationship is many-to-many. The SDOrgPostalAddr table should not appear as model entity because it is only the many-to-many link table

With this model and changing your view model to...

public class CustomerDetails
{
    public AccountDefinition AccountDefinition {get; set;}
    public SDOrganization SDOrganization {get; set;}

    public ICollection<AaaPostalAddress> AaaPostalAddresses { get; set; }
}

...you should be able to get the result using:

var customerDetails = context.AccountDefinitions
    .Where(a => a.OrgID == givenOrgID)
    .Select(a => new CustomerDetails
    {
        AccountDefinition = a,
        SDOrganization = a.SDOrganization,
        AaaPostalAddresses = a.SDOrganization.AaaPostalAddresses
    })
    .SingleOrDefault();

You can also fetch the same data by eager loading the AccountDefinition entity together with the needed navigation properties:

var accountDefinition = context.AccountDefinitions
    .Include(a => a.SDOrganization.AaaPostalAddresses)
    .SingleOrDefault(a => a.OrgID == givenOrgID);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top