How to bind Sql View to an Entity Framework object

If you do not want to create an Entity and to configure this one with the ToTable() to the name of your view, you can use direct method from the context to call the database and bind the result into a class.

Here is how to do it with the ToTable method:

    public class WorkoutConfiguration : EntityTypeConfiguration<Workout>
        public WorkoutConfiguration()
            base.ToTable("dbo", "ViewNameHere");
            base.HasMany(d => d.Sessions)

Here is how to do it with a direct SQL statement:

var workouts = _dbContext.Database.SqlQuery<Workout>("select * from dbo.Workout")

The SqlQuery acts the same with the binding of value than with Entity Framework. Every fields is mapped with the corresponding methods. You can use AS statement to change the return value of some fields to be the same name of your methods.

var workouts = _dbContext.Database.SqlQuery<Workout>("select id as ID, name as nameFR from dbo.Workout")

At first, the last solution seems to be faster and fine but consider the first one if you are using table or view because it’s better. Better because you do not have to handle a string with a SQL query. If the database change, you won’t notice any problem until the query is executed. It’s more a work around than a good “enterprise” solution. But, the last one can be a good compromise if you need to use stored procedure. Nevertheless, always ask yourself in the long term what will be the repercussion of your choice.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.