Azadrum
Azadrum

Reputation: 746

How to get entities from context before saving the unitofwork Pattern to calculate a field via previously added entities?

Im a new user in stackoverflow and this is my first question hope i wont be breaking any rules :)...

In my MVC3 project with EF4 and UnitOfWork Pattern,

When adding a new entity i have to check freshly added entities and the ones already stored in the database and calculate a column in new entity.

The problem is if i get the values from database newly added entities will not taken into consideration.

I overcome the problem via saving the unitofwork after each entity insert. But this means saving the current state of the context every time that specific entity is inserted.

I would like to know if this will bring some performance issues in the future. if so is there any other way to solve the issue?

Here is the relative code about the issue (simplified)

Model :

public class Group
    {
        public Guid GroupId { get; set; }
        public int Code { get; set; }

    }

Controller :

        UserGroup Group1 = new Group()
        {
            UserGroupId = Guid.NewGuid(),
            Code = (int)Math.Pow(2, (unitOfWork.GroupRepository.Get().Count()));
        };
        unitOfWork.GroupRepository.Insert(Group1);


        UserGroup Group2 = new Group()
        {
            UserGroupId = Guid.NewGuid(),
            Code = (int)Math.Pow(2, (unitOfWork.GroupRepository.Get().Count()));
        };
        unitOfWork.GroupRepository.Insert(Group2);

Insert Method : (derived from generic repository not to send all the repository pattern)

    public virtual void Insert(Group grouptoadd)
    {
        UnitOfWork unitOfWork = new UnitOfWork(Context);
        dbSet.Add(grouptoadd);
        unitOfWork.Save();
    }

If i won't save UnitOfWork inside the Insert Method of GroupRepository class, When the Code of Group2 is calculated it wont get the Group1 into consideration.

Saving the unitOfWork inside the insert Method doesnt seem right. Tried to get the values from Context

(int)Math.Pow(2, (Context.Groups.Count()));

this code always returns 1. I could see the Entities inside the Context in debug mode but Count returns 0.

In the end i need : (newly added entities + entities stored in the database).Count()

Upvotes: 0

Views: 635

Answers (2)

achekh
achekh

Reputation: 1106

You might want to use DbSet's Local property. Refer the article Why can I not see the property Local when using Entity Framework? if you don't use DbSets.

Upvotes: 1

hopper
hopper

Reputation: 4338

You need to use a different context. try to initialize a different context at it will work.

Upvotes: 0

Related Questions