我正在使用代码优先方法流式 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.
}
}
请建议。谢谢