Monday 8 May 2017

DbContext and related classes are not guaranteed to be thread safe [Rsolved]

Hello, I am getting following error from my DbContext while accessing a query in Entity Framework.
Let me tell you complete code snippet of .net and database query.

Error which I was getting is:
An exception of type System.InvalidOperationException occurred in EntityFramework.dll but was not handled in user code The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

My DbSet in Code First are :
 
public DbSet<EmpDetails > empDetails { get; set; }
 
 
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Web.Script.Serialization;
    [Table("EmpView", Schema = "dbosc")]
    public partial class EmpDetails : IDataEntity
    {
//…
    }


What I did first?
I went to sql server management studio and tried to execute the view with select statement.
Select * from EmpView

But I got 
The server principal "dbuser" is not able to access the database "dbname" under the current security context.

Then I went through the View syntax and I found there were join between different database on which dbuser doesn't have access.
..  FROM    dbname.dbosc.Person
            JOIN otherdb.dbo.exdetails ….

Initially dbuser ha access of otherdb but due to some reason missed.
So what I did, I executed following script and I got resolved this problem.

sp_change_users_login [ @Action = ] 'action' [ , [ @UserNamePattern = ] 'user' ] [ , [ @LoginName = ] 'login' ] [ , [ @Password = ] 'password' ] [;]


sp_change_users_login 'update_one' 'dbuser' 'dblogin'