EF中能否将视图映射为实体模型的导航属性?
将数据库视图映射为实体的导航属性可行吗?
问题场景
现有实体类First:
public class First { public int FirstId {get;set;} public string Field1 {get; set;} public string Field2 {get; set;} public int PersonId {get; set;} public int AccountId { get; set;} // 期望添加的导航属性 public VUsefulInformation VUsefulInformation { get; set; } }
以及对应数据库视图的类VUsefulInformation:
public class VUsefulInformation { public int PersonId {get; set;} public int AccountId { get; set;} public string Color {get;set;} public int Length {get;set;} }
需求是把VUsefulInformation作为First的导航属性,但视图中没有任何指向First表的关联字段,配置Fluent API时遇到了无法指定反向导航的问题:
builder.HasOne<VUsefulInformation>(x => x.VUsefulInformation).WithMany(x => x....?);
解答
这种配置逻辑上是可行的,EF Core完全支持将视图作为实体的单向导航属性,不需要视图知晓First表的存在。
具体配置方式
因为是单向导航(仅First指向视图,视图类没有对应的集合导航属性),可以使用WithMany()的无参数重载,同时指定联合关联键即可:
// 在First实体的Fluent API配置中 builder.HasOne(f => f.VUsefulInformation) .WithMany() // 无需指定反向导航,使用无参数重载 .HasForeignKey(f => new { f.PersonId, f.AccountId }) // First的关联字段 .HasPrincipalKey(v => new { v.PersonId, v.AccountId }); // 视图的匹配字段
关键注意点
- 必须保证视图
VUsefulInformation中PersonId和AccountId的组合是唯一的,否则EF加载导航属性时会出现匹配异常(一个First实例只能对应一条视图记录)。 - 视图是只读对象,通过这个导航属性只能做查询操作,EF不支持通过它更新或插入视图数据。
内容的提问来源于stack exchange,提问作者Francis Ducharme
相关产品推荐
相关产品推荐

