Load a not mapped attribute with EF Core

c# entity-framework entity-framework-core

Question

I attempt to invoke a stored method to load an object using EF Core. Fluent mapping links the object to a table that excludes some of the columns chosen by the stored function.

In the entity setup, the specified attributes that do not already exist as table columns are ignored:

        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);

The saved procedure's name is as follows:

await SalesContext.CustomerLocation
            .FromSql("GetCustomersByLocation @latitude={0}, @longitude={1}, @radius={2}", lat,
                lon, radius)
            .ToListAsync();

The ignored columns are not mapped to the object when the query is run. When invoking a stored procedure, is it possible to map the ignored fields to the entity? If not, do I need to construct a different entity just for the stored method or anything similar?

1
1
9/10/2018 10:24:58 AM

Accepted Answer

When you use the fluent api's ignore function on a column, SQL Server will not generate that column for you (Ignores it).
Your constructed query will be used to generate certain columns from your stored procedure, and the names of these columns must coincide with the names of the properties on your object.
For instance, your process provides you with a database in SQL Server that has the following fields and matches data types to your class:

  1. Latitude
  2. Longitude
  3. Radius
  4. Distance

After that, you need to create a class for your procedure:

public class LocationProcedure {
   public string Latitude {get;set;}
   public string Longitude {get;set;}
   public string Radius {get;set;}
   public string Distance {get;set;}
}

along with adding a database set of this kind to your database context using[NotMapped] Attribute:

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

This shouldn't be a table in the database, according to the property.

Finally, the new dbset allows you to utilize your process.CustomerLocation then map the outcomes to the LocationProcedure class.

await SalesContext.CustomerLocation
            .FromSql("GetCustomersByLocation @latitude={0}, @longitude={1}, @radius={2}", lat,
                lon, radius)
            .ToListAsync();
2
9/10/2018 11:10:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow