DBContext Entity State

Jan 14, 2013 at 4:08 PM

HI, I have been using Effort using the CreatePersistent connection factory method, I have noticed that the state of entities is always detached see the code below.

what is wrong with what I am doing??

    public sealed class MockDbContext : DbContext
    {
        public MockDbContext(DbConnection connection)
            : base(connection, true)
        {
            var entities = CreateEntityList();
            
            foreach (var entity in entities)
            {
                Entities.Add(entity);
            }
            var state = Entry(entities.First()).State; // Should be Added But it is always Detached
            SaveChanges();
            state = Entry(entities.First()).State; // Should be Unchanged But it is Detached
        }

        public DbSet<Entity> Entities { get; set; }

        private IEnumerable<Entity> CreateEntityList()
        {
            var j = 60;
            for (var i = 0; i < 50; i++, j--)
            {
                yield return new Entity { Id = i, Name = "name" + j };
            }
        }
    }


    public class Entity : IEntity
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage="Name is required"), StringLength(20, ErrorMessage="Name maximum length is 50 characters")]
        public string Name { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? CreatedDate { get; set; }
        public string LastUpdatedBy { get; set; }
        public DateTime? LastUpdatedDate { get; set; }
    }

Coordinator
Jan 18, 2013 at 10:15 AM
Edited Jan 18, 2013 at 10:16 AM

Effort works in the lower (logical, storage) layers of Entity Framework, so issues that is related to the upper (conceptual) layers are not likely caused by it. I checked your example code with SqlConnection and it does exactly the same as you described.

The problem is caused by the fact that the following expressions evaluate your enumerable method three times. Each evaluation creates new objects.

foreach (var entity in entities)

Entry(entities.First()).State

Entry(entities.First()).State

 

The entities.First() expression returns a new instance of the entity that obviously was not added in the loop.  You should have created the "entities" variable like this:

var entities = CreateEntityList().ToList();