简体   繁体   中英

return result with non-existing model entity - EF .net Core 3

I would like to return a result by SP for columns which actually does not exist in current model entities. Currently I am only able to return result which are one of the current model(s).

   [HttpGet]
    public async Task<ActionResult> getAllSalaryRanks()
    {
        HttpResponseMessage response = new HttpResponseMessage();

        using(db963Context context = new db963Context())
        {
            var ranks = context.IoVouchersSalaryRanks.FromSqlRaw("EXEC ioVouchers_sp_SalaryRanks").ToList();

            return Ok(ranks);
        }

    }

In the above example I will get an exception says: The required column 'foo' was not present in the results of a 'FromSql' operation.

Basically IoVouchersSalaryRanks is one of my models,so the result's columns should be the exact as the model entity. How can I add a custom model entity, so the SP will return a result matches to that custom model?

It means that column foo is not returned by your stored procedure. Try to:

  • add your column Foo into your SELECT statement
  • or use [NotMapped] for your Foo column. This attribute can be used for properties of an entity class for which we do not want to create corresponding columns in the database

Your stored procedure ioVouchers_sp_SalaryRanks must return a result that can be mapped to your entity IoVouchersSalaryRank

If it returns a custom results, you have to implement this way:

string query = "EXEC ioVouchers_sp_SalaryRanks";

var ranks = context.Set<CustomModel>().FromSqlRaw(query).ToList();

where CustomModel is a new entity where the properties can be mapped to the columns that are returned by your SP. So, if it returns only column foo with type string, it would look like this:

public class CustomModel
   {
       public string Foo{ get; set; }
   }

Add the CustomModel to the dbcontext in the method OnModelCreating

        modelBuilder.Entity<CustomModel>().HasNoKey();

I have a blog post that explains it, you can have a look here >> https://mohamedsahbi.com/2019/05/22/raw-queries-with-entity-framework-core/

Update: my blog was related to EF Core 2.1. So, I just updated the answer to work with EF Core3.1 You can find also a GitHub repos with a sample for EF Core 3.1 https://github.com/MohamedSahbi/RawQueryWithEFCore/tree/master/SampleWithEFCore/SampleWithEFCore3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM