Can I create a readonly connection for my EDM without a read-only user?

94 Views Asked by At

I'm writing an app that connects to 2 different database schemas. One of these schemas should be read-only. Is there a way to set the connection as read-only? I don't have the ability to create a read-only user.

2

There are 2 best solutions below

0
Tengiz On

set connection Mode property to ModeRead

con.Mode = 1

2
Eranga On

A better approach for this would be to disable your UI elements based on whether the user is allowed to modify the data or not. Problem with your approach is that EF API is not designed to work with read only mode. Calling SaveChnages when using a readonly connection with throw an exception.

You can do something like this to prevent EF from updating on a readonly connection.

public class MyContext : DbContext
{
    private bool isReadOnly;
    public MyContext(string conn, bool isReadOnly)
    :base(conn)
    {
         this.isReadOnly = isReadOnly;
    }

    public override int SaveChanges()
    {
         if (isReadOnly)
         {
              return 0; //or throw exception
         }

         return base.SaveChanges();
    }
}

With ObjectContext this is bit tricky. You can unset all changes in SavingChanges event.