Entity framework Core Raw SQLQueries with custom model

后端 未结 4 1412
难免孤独
难免孤独 2021-02-14 20:39

Using Entity Framework 6, I was able to use execute a Raw SQL Query and use a custom model which was not defined in the DBContext in order to store the output of the query. A si

4条回答
  •  醉话见心
    2021-02-14 21:09

    Here's how I was able to get this working (for completeness):

    MyModel.cs:

    public class MyModel
    {
        // The columns your SQL will return
        public double? A { get; set; }
        public double? B { get; set; }
    }
    

    Add class that just inherits from your original EF context class (i called mine DbContextBase):

    public class DbContext : DbContextBase
    {
        public virtual DbSet MyModels { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            // Necessary, since our model isnt a EF model
            modelBuilder.Entity(entity =>
            {
                entity.HasNoKey();
            });
        }
    }
    

    Use that class (instead of your original EF context class):

    // Use your new db subclass
    using (var db = new DbContext())
    {
        var models = await db.MyModels.FromSqlRaw(...).ToListAsync();    // E.g.: "SELECT * FROM apple A JOIN banana B ON A.col = B.col"
    }
    

    Notes:

    • If you need to, just use FromSqlInterpolated instead of FromSqlRaw
    • The "db context" subclass allows you to update EF models without affecting your "polyfill" code
    • Works with SQL Server stored procs that return only 1 result set

提交回复
热议问题