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

时间:2018-09-10 10:24:59

标签: c# entity-framework entity-framework-core

我尝试通过调用存储过程来使用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 个答案:

答案 0 :(得分:2)

在列上使用fluent api的ignore方法时,它不会在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]属性将这种类型的dbset添加到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();