![](/img/trans.png)
[英]How to map identifying relationship in Entity Framework 5 code first child entity with multiple mutually exclusive parent entities
[英]Map a sql view to already defined multiple entities in Entity Framework Code first?
我正在使用代碼優先方法fluent API將sql表映射到實體,如下所示:
public class ProjectEntities : DbContext
{
public ProjectEntities ()
: base("name=ProjectEntities ")
{
}
public DbSet<UserEntity> UserEntity { get; set; }
public DbSet<AddressEntity> AddressEntity { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserEntityMapper());
modelBuilder.Configurations.Add(new AddressEntityMapper());
}
}
映射器的位置為:
public class AddressEntityMapper : EntityTypeConfiguration<AddressEntity>
{
public AddressEntityMapper()
{
ToTable("Address");
HasKey(m => m.AddressID);
HasRequired(m => m.UserEntity).WithMany(b => b.AddressEntity);
Property(p => p.AddressKey).HasColumnName("ADDRESSID");
Property(p => p.UserID).HasColumnName("User_id");
Property(p => p.Address1).HasColumnName("ADDRESS1");
Property(p => p.Address2).HasColumnName("ADDRESS2");
Property(p => p.Address3).HasColumnName("ADDRESS3");
Property(p => p.City).HasColumnName("CITY");
Property(p => p.State).HasColumnName("STATE");
Property(p => p.ZipCode).HasColumnName("ZIPCODE");
}
}
和用戶映射器:
public class UserEntityMapper : EntityTypeConfiguration<UserEntity>
{
public UserEntityMapper()
{
ToTable("User");
HasKey(m => m.UserID);
Property(p => p.UserID).HasColumnName("UserID");
Property(p => p.FirstName).HasColumnName("FIRSTNAME");
Property(p => p.LastName).HasColumnName("LAST_NAME");
Property(p => p.MiddleInitial).HasColumnName("MIDDLEINITIAL");
}
}
這些東西工作正常,現在我們必須更改邏輯以獲取信息。 現在公司決定使用sql視圖來獲取完整的用戶信息,以便您將所有用戶信息集中在一個地方。 現在,我不想重做/創建另一個映射器,該映射器映射來自兩個表的所有字段,這些表均來自sql視圖。
所以我的問題是我們是否可以聲明另一個將這兩個映射器映射為的映射器:
public class UserFullEntityMapper : EntityTypeConfiguration<UserEntity, AddressEntity>
{
public UserFullEntityMapper()
{
ToTable("vw_user");
///Declare the auto mapping here to the fields from above entities to columns retuned from sql view.
}
}
請提出建議。 謝謝
您應該為視圖定義一個新實體:
public class YourViewName
{
// properties from UserEntity
// properties from AddressEntity
}
並使用以下映射:
public View_mapping:EntityTypeConfiguration<YourViewName>
{
public View_mapping()
{
ToTable("vw_user");
// other mappings
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.