【问题标题】:Load a not mapped attribute with EF Core使用 EF Core 加载未映射的属性
【发布时间】:2018-09-10 19:10:58
【问题描述】:

我尝试通过调用存储过程来使用 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();

执行查询时,忽略的列不会映射到实体。在调用存储过程时是否有可能将忽略的字段映射到实体,或者我是否必须为存储过程创建另一个实体或类似的东西?

【问题讨论】:

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


    【解决方案1】:

    当你在列上使用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();
    

    【讨论】:

    • 你成就了我的一天!这对我来说不是最终的解决方案,但你让我走上了正确的道路。由于新实体有一个复合键,我需要通过流畅的映射来声明键,而不需要将实体绑定到表并且映射有效。
    • Ef 还需要每个 dbset 有一个名为 Id 的列或另一个主键。否则它会抛出异常。
    • 使用 DbSet[NotMapped] 属性不会忽略应用迁移后在数据库中创建适当的表
    • 是的,[NotMapped] 应该装饰 LocationProcedure 类,而不是 DbSet
    • 如果我在动态构建的 sql 中选择列怎么办?然后我没有得到我的未映射字段的价值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2018-03-06
    • 2015-04-06
    • 2020-06-06
    • 2023-02-10
    • 2020-01-01
    相关资源
    最近更新 更多