使用实体框架的存储过程在同一模型中的多个复杂类型实例

时间:2015-04-20 16:21:27

标签: c# entity-framework stored-procedures entity-framework-6

我正在使用Entity Framework Code First,我有以下场景,我有一个会员模型,有2种类型的地址,居住地址和通信地址。地址是一个复杂类型,因此我在同一个模型中有2个相同复杂类型的实例。我从这里读到这个: Entity framework complex type multiple instances in one model,但不涉及存储过程。 我的情况几乎相同,但使用存储过程。

以下是我的模型和商店过程中使用的查询。

地址Complext类型:

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public State State { get; set; }
    public string Zip { get; set; }
    public Country Country { get; set; }
    public AddressType Type { get; set; }
}

会员类:

public class Member
{
    public Address ResidenceAddress { get; set; }
    public Address CorrespondenceAddress { get; set; }
}

调用存储过程的方法:

public Member GetMember(string memberId)
{
    using (var entityContext = new AmigosContext())
    {
        var sqlParams = new[]
        {
            new SqlParameter("memberId", memberId), 
        };
        var result = entityContext.Database.SqlQuery<MemberInfoEnhanced>("EXEC GetMember @MemberId ", sqlParams);

        return result.FirstOrDefault(); 
    }
}

存储过程内的SQL查询:

SELECT  gcar.AddressLine1 AS ResidentAddressLine1
     , gcar.AddressLine2 AS ResidentAddressLine2
     , gcityr.Name AS ResidentCity
     , gcar.State AS ResidentState
     , gcar.Zip AS ResidentZip
     , gcountry.ISOAlpha AS ResidentCountryISOCode
     , gcar.AddressTypeId AS ResidentAddressTypeId
     , gcac.AddressLine1 AS CorrespondenceAddressLine1
     , gcac.AddressLine2 AS CorrespondenceAddressLine2
     , gcityc.Name AS CorrespondenceCity
     , gcac.State AS CorrespondenceState
     , gcac.Zip AS CorrespondenceZip
     , gcac.AddressTypeId AS CorrespondenceAddressTypeId

FROM Member pm WITH (NOLOCK)ON pm.MemberId = pme.MemberId
       LEFT JOIN Generic_ContactAddress gcar ON gcar.ContactBaseId = pm.ContactBaseId -- get resident address
                                                    AND gcar.AddressTypeId = 2 --Physical Address
       LEFT JOIN Generic_Country gcountry ON gcountry.CountryId = gcar.CountryId -- to get the ISOAlpha code
       LEFT JOIN Generic_City gcityr ON gcityr.CityId = gcar.CityId --to get the resident CityName
       LEFT JOIN Generic_ContactAddress gcac ON gcac.ContactBaseId = pm.ContactBaseId -- to get correspondence address
                                                    AND gcac.AddressTypeId = 1 --Correspondence (Mailing) Address
       LEFT JOIN Generic_City gcityc ON gcityc.CityId = gcar.CityId --to get the correspondence CityName

WHERE pm.MemberId = @MemberId

有没有办法将不同的地址列映射到不同的复杂类型?

由于

0 个答案:

没有答案