我尝试通过调用存储过程来加载具有 EF Core 的实体。 实体通过流畅映射映射到表,该映射不包含存储过程选择的所有列。
在实体配置中忽略不作为表列存在的选定字段,如下所示:
modelBuilder.Entity<CustomerLocationEntity>().Ignore(c => c.Latitude);
modelBuilder.Entity<CustomerLocationEntity>().Ignore(c => c.Longitude);
modelBuilder.Entity<CustomerLocationEntity>().Ignore(c => c.Radius);
modelBuilder.Entity<CustomerLocationEntity>().Ignore(c => c.Distance);
存储过程的调用方式如下:
await SalesContext.CustomerLocation
.FromSql("GetCustomersByLocation @latitude={0}, @longitude={1}, @radius={2}", lat,
lon, radius)
.ToListAsync();
执行查询时,忽略的列不会映射到实体。调用存储过程时是否有可能将忽略的字段映射到实体,或者我是否必须为存储过程创建另一个实体或类似的东西?
当你在列上使用流畅 api 的忽略方法时,它不会在 sql 服务器中创建该列(忽略它(。
存储过程结果将根据创建的查询提供一些列 这些列名称必须与实体上的属性名称匹配。
例如,您的过程为您提供了一个表,其中包含这些列以及 sql Server 和类中的匹配数据类型:
- 纬度
- 经度
- 半径
- 距离
然后,您应该为过程创建一个类:
public class LocationProcedure {
public string Latitude {get;set;}
public string Longitude {get;set;}
public string Radius {get;set;}
public string Distance {get;set;}
}
并将这种类型的数据库集添加到具有[NotMapped]
属性的数据库上下文中:
[NotMapped]
public DbSet<LocationProcedure> CustomerLocation {get; set:}
该属性告知这不应该是数据库中的表。
最后,您可以将过程与新的数据库集CustomerLocation
一起使用,然后它将结果映射到LocationProcedure类。
await SalesContext.CustomerLocation
.FromSql("GetCustomersByLocation @latitude={0}, @longitude={1}, @radius={2}", lat,
lon, radius)
.ToListAsync();