Reputation: 8451
I am using EF to update my database.
I first query the database based upon some criteria. This returns the record I am expecting (or returns null). Naturally during this query, there is a slight delay as it executes the query.
I then change a property in this case a nullable boolean from false to true or create a new entry.
I then add this object to my Entities, and finally choose myEntitiy.SaveChanges(). This does not seem to execute. There is no delay. Yet the code passes to the next line, so no exception is thrown.
This is what I have
public class MyCompany : AbstractCompany
{
public override bool UpdateStatus(string emailAddress, bool isOptIn)
{
var personDetail = (from a in base.Entities.MyCompanyTable
where a.EmailAddress == emailAddress
select a).SingleOrDefault();
if (personDetail == null)
{
personDetail = new MyCompanyTable();
personDetail.EmailAddress = emailAddress;
}
personDetail.IsSubscribed = isOptIn;
base.Entities.MyCompanyTable.Add(personDetail); //also tried attach, same issue over
return base.SaveData();
}
}
And my base class is
public abstract bool UpdateStatus(string emailAddress, bool isOptIn);
protected Entities Entities
{
get { return new Entities(); }
}
protected bool SaveData()
{
var x = Entities.GetValidationErrors();//returns 0 items
try
{
Entities.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
What have I done wrong?
Upvotes: 1
Views: 47
Reputation: 4783
Entity Framework uses change tracking to detect changes in any entities in the current context.
However, your Entities
property instantiates a new instance of your context everytime it is called. So when you query you use one context and then when you save you use another! EF has no way to detect that you made any changes!
It would be best to instantiate your context in the base class' constructor:
public abstract class BaseClass
{
protected BaseClass()
{
Entities = new Entities();
}
protected Entities Entities { get; private set; }
}
That should fix it up.
Upvotes: 5