Entity framework Core Raw SQLQueries with custom model

后端 未结 4 1410
难免孤独
难免孤独 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:22

    follow these steps:

    Create your model

    Probably it could be better if you can reduce it to a model as generic as possible but it's not a must:

    public class MyCustomModel
    {
       public string Text { get; set; }
       public int Count { get; set; }
    }
    

    Add it to your own DbContext

    Create DbSet for your custom model

    public virtual DbSet MyCustomModelName { get; set; }
    

    Keep in mind to specify your custom model has no key

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        ...
    
        modelBuilder.Entity().HasNoKey();
    }
    

    Use it from your dbContext instance

    async public Task> GetMyCustomData()
    {
        var rv = new List();
        using (var dataContext = new DbContext())
        {
            var sql = @"
                select textField as 'Text', count(1) as 'Count'
                from MyTable";
            rv = await dataContext.Set().FromSqlRaw(sql).ToListAsync();
        }
        return rv;
    }
    

提交回复
热议问题