实体框架使用条件将两个表映射到一个类

时间:2015-09-22 09:33:58

标签: c# entity-framework ef-code-first entity-framework-6

我正在尝试将一个类映射到两个数据库表。我有一个Person类,它映射到一个Person表和一个Address表。我的问题是我只想选择地址表的主地址行(IsPrimary = 1),我找不到或弄清楚如何执行此操作。

我正在使用Entity Framework v6 CodeFirst并尝试创建EntityTypeConfiguration<T>

域类是......

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // Primary Address
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public string AddressPostCode { get; set; }
}

,数据库表看起来像这样......

Table: Person
Int PersonId (PK)
Varchar(20) FirstName Not Null
Varchar(20) LastName Not Null

Table: Address
Int         AddressId     (PK)
Int         PersonId      (FK)
Varchar(25) AddressLine1  Null
Varchar(25) AddressLine2  Null
Varchar(25) AddressLine3  Null
Varchar(10) PostCode      Not Null
Bit         IsPrimary     Not Null

基本上一个人可以有多个地址,但只有一个主要地址。

1 个答案:

答案 0 :(得分:2)

如果您正在使用Entity Framework,那么您可能拥有以下具有一对多关系的类:

public class PersonEntity
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<AddressEntity> Addresses { get; set; }
}

public class AddressEntity
{
    public int AddressId  { get; set; }  
    public int PersonId { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public string AddressPostCode { get; set; }
    public bool   IsPrimary{ get; set; }
}

正如您在问题中提到的,这是人物视图模型:

public class PersonViewModel
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // Primary Address
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public string AddressPostCode { get; set; }
}

最后,您可以使用以下linq代码:

var result = ctx.PersonEntity
.Where(c => c.Addresses.FirstOrDefault(X = > X.IsPrimary == true)).ToList();

var personViewModels = result
.Select(c => new PersonViewModel{
PersonId = c.PersonId ,
FirstName = c.FirstName , 
LastName = c.LastName,  
AddressLine1 = c.Addresses != null ? c.Addresses.FirstOrDefault().AddressLine1 : String.Empty , 
AddressLine2 = c.Addresses != null ? c.Addresses.FirstOrDefault().AddressLine2 : String.Empty ,  
AddressLine3 = c.Addresses != null ? c.Addresses.FirstOrDefault().AddressLine3 : String.Empty  });