Sasa Sasa - 3 months ago 13
Vb.net Question

Can I call SaveChanges when using raw SQL Query in EF6

I want to use sql raw query for better performance.

I was wondering if I could use context the same way as if I committed a query with linq. If I bind collection to dgv.DataSource and made some (update) could I call

db.SaveChanges()
to store the data in the database.

Example:

Using context = New BloggingContext()
Dim blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList()
datagridview1.dataSource = blogs

' if I made some changes in datagridview1 could I
' use SaveChanges to commit any changes on button click

context.SaveChanges()

End Using

Answer

The DbSet.SqlQuery method returns object that are tracked by the context :

By default, the entities returned are tracked by the context (MSDN)

(note that Database.SqlQuery results never tracked by the context)

If you change your entities using Entity Framework the SaveChanges method will persist changes.

Using context = New BloggingContext()
    Dim blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList()

    blogs.First().Title = "new Title"

    context.SaveChanges() ' new Title will be persisted on database

End Using

By the way, depending on the kind of datagridview you are using (webform, winform, WPF, etc.), you will have to attach the modified entities to the context that will be used to save changes.

Comments