Gerald Gonzales
Gerald Gonzales

Reputation: 533

Serialization issue with entity framework and sql session state

I have this entity and dbcontext on my application:

[Serializable, Table("calc.Student")]
public class Student
{
    public int Id { get; set; }
}

public StudentDbContext() : base("name=DefaultConnection") 
{ 

}

public DbSet<Student> Students { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

My DTO class:

[Serializable]
public class StudentDTO
{
    public int Id { get; set; }
}

My api controller:

public IQueryable<StudentDTO> Get()
{
    var students = from b in db.Students
                   select new StudentDTO()
                   {
                       Id = b.Id
                   };
    return students ;
}

Now my problem here is with my session state. On my web.config file, I stated the code below so I can store my session on the database:

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" cookieless="false"

With this line of code, I am receiving this error:

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

I thought returning a DTO object would resolve my problem but now I am stuck.

Any ideas?

Upvotes: 1

Views: 1380

Answers (2)

Gerald Gonzales
Gerald Gonzales

Reputation: 533

I forgot to provide my answer to my problem here but in case others are having the same problem.

The cause is this line below on my StudentRepository class.

StudentDbContext context = new StudentDbContext();

Even though the StudentRepository has a signature of [Serializable], it has member which can't be serialized.

The fix is to only declare the context inside the methods.

public IEnumerable<Student> GetAllStudent()
{
    using (var context = new StudentDbContext())
    {

    }
}

No need to use the DTO object.

Upvotes: 1

JotaBe
JotaBe

Reputation: 39045

This has nothing to do with EF. As stated it the error that you're showing the problem is that you'¡re trying to store an object in Session which cannot be serialized or is a MarshalByRef object.

You need to find the offending Session["xyz"] = myObject; and make the class of myObject serializable.

Besides, you need to configure your server to allow SQL Server Session State: HOW TO: Configure SQL Server to Store ASP.NET Session State. Just in case you didn't it.

Please, follow the link in this comment from Session-State Modes:

Objects stored in session state must be serializable if the mode is SQL Server. For information on serializable objects, see the SerializableAttribute class.

Upvotes: 0

Related Questions