1

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
5
  • give an example of changes the you want to do Commented Mar 26, 2015 at 13:22
  • @mohsen.d I change data from cell DGV . Or in the same time i add new row. All kind of changes i do to DGV. Just like you can do if you are using Ado.net and bind collection to grid and make some changes and then call ADAPTER.UPDATE(DATASET). See my edit Commented Mar 26, 2015 at 13:28
  • Are you sure that using raw SQL query improve performance ? have you made performance test ? Commented Mar 26, 2015 at 13:33
  • @CyrilDurand codeproject.com/Articles/783203/… Commented Mar 26, 2015 at 13:44
  • @dejan the codeproject article explains how to use custom SQL. In its case, he could have used the .Include method to include addresses in the same query or use a projection .SelectMany(p => p.Addresses).Select(a => new {FirstName = a.Person.FirstName, Stree = a.Street, ...}). This article doesn't use correctly EF and I don't recommend you to use raw SQL query for such simple query. If you have performance issue with EF, feel free to ask a new question :-) Commented Mar 26, 2015 at 17:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.