为了账号安全,请及时绑定邮箱和手机立即绑定

使用 EF Core 加载未映射的属性

使用 EF Core 加载未映射的属性

C#
POPMUISE 2022-01-09 17:42:17
我尝试通过调用存储过程来使用 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();执行查询时,忽略的列不会映射到实体。调用存储过程时是否有可能将忽略的字段映射到实体,或者我是否必须为存储过程创建另一个实体或类似的东西?
查看完整描述

1 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

当您在列上使用fluent api的忽略方法时,它不会在sql server中创建该列(忽略它)。
您的存储过程结果将根据您创建的查询为您提供一些列,并且这些列名称必须与您的实体上的属性名称匹配。
例如,您的过程为您提供了一个包含这些列的表以及 sql server 和您的类中的匹配数据类型:

  1. 纬度

  2. 经度

  3. 半径

  4. 距离

然后你应该为你的过程创建一个类:

public class LocationProcedure {

   public string Latitude {get;set;}

   public string Longitude {get;set;}

   public string Radius {get;set;}

   public string Distance {get;set;}

}

并使用[NotMapped]属性将这种类型的数据库集添加到您的 dbContext 中:


[NotMapped]

public DbSet<LocationProcedure> CustomerLocation {get; set:}

该属性告诉这不应该是数据库中的表。


最后,您可以将您的过程与新的 dbset 一起使用CustomerLocation,然后它将结果映射到LocationProcedure类。


await SalesContext.CustomerLocation

            .FromSql("GetCustomersByLocation @latitude={0}, @longitude={1}, @radius={2}", lat,

                lon, radius)

            .ToListAsync();


查看完整回答
反对 回复 2022-01-09
  • 1 回答
  • 0 关注
  • 625 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号