Posts Tagged ‘Entity Framework’

Enity Framework: Unable To Delete Entity Because Primary End Of Foreign Key Constraint Has Been Deleted

November 23, 2011

I got this error even though the Foreign Key constraint had been deleted from the database and I had re-executed all my EF Template files, had refreshed my Model from the database and had deleted the relevant Navigation propertry from my Model.

Thing is , I had forgotten to physically delete the Association in the Model Designer .edmx file. When I did that and then re-ran my Model Template file all was well.

So I reckon I had only refreshed the secondary (referencing) table in the FK side. Next time I will refresh the primary (referenced) table as well.

That’s all. Get back to what you were doing. The door is the wooden thing in the wall behind you.

Advertisements

Entity Framework Type FixupCollection`1 is not marked as serializable.

October 21, 2011

Entity Framework Autogenerated Classes Not Marked as Serializable.

This error comes about while trying to Serialize an EntityFramework Entity that has Associations. I got my error after creating a New entity, saving it, then doing Update on the newly created entity.

A workaround is to add the [Serializable] attribute to the FixUpCollection class, which is located in your .cs file. So, if your EF Template is called StudentEnrolment.tt then FixupCollection is located in StudentEnrolment.cs. Make FixupCollection look like this:

[Serializable]
public class FixupCollection : ObservableCollection

The permanent fix is to modify your Entity Framework template file to make sure that every time your template is run and your Entity classes regenerated then the Serializable attribute is plonked on top of the EF FixupCollection class.

So edit your equivalent StudentEnrolments.tt and find the line where FixupCollection is generated and simply insert the text “[Serializable]” above it, exactly as you would in your class definition, like so:


#>
// An System.Collections.ObjectModel.ObservableCollection that raises
// individual item removal notifications on clear and prevents adding duplicates.
[Serializable]
public class FixupCollection : ObservableCollection
{

All credit to marc_s at Stack Overflow who wrote this and Ross Pace who linked to it from here.

Once again for lovers of Stack Dumps, here’s the full error:

Type 'SubstationLoad.Data.Model.FixupCollection`1[[SubstationLoad.Data.Model.Substation, SubstationLoad.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'SubstationLoad.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Adding An Additional Item To A Collection In Entity Framework With Repository Pattern

October 13, 2011

My application has Entities named ‘Hazards’ and ‘Hazard Groups’. A HazardGroup contains many Hazards and the Hazards may be moved from one HazardGroup to another via a Dialog Box.

I found when trying to add an existing Hazard to an existing HazardGroup that I was getting (to paraphrase) ‘Cannot create association: Objects were created in different Data Contexts’ error message. So I needed to put the Hazard and the HazardGroup in the same Object Context.

Here’s how I ended up doing it:

using (var ctx = new HazardContext())
{ {
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.HazardGroups.Attach(SelectedHazardGroup);
ctx.Hazards.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
}

Just to make it spicier I was also using the Repository Pattern, so I had to make sure that my SelectedHazardGroup was attached to the active Repository, like so:

using (var ctx = new HazardContext())
{
IRepository (Of HazardGroup) repo =
new Repository (Of HazardGroup)(ctx);

repo.Attach(SelectedHazardGroup);
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.Substations.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
repo.SaveChanges()
}

HTH.

ObjectDisposedException EntityFramework

September 21, 2011

I had a using clause around my call to Entity Framework like so:

using (var ctx = new SubstationLoadContext())
{
IRepository repo =
new Repository(ctx);

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits();
}

Subsequently while performing a LINQ query on AreaSummations I received the fiendish ObjectDisposedException. Porquoi ?

Some quick Googling told me that since my context variable was being disposed before I performed the query I should force the creation of an in-memory List in order to detach from the database i.e. I should do a .ToList() like so:

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits.ToList();

But my repo method was already doing a .ToList(). I was already detached from the database wasn’t I? Nyet.

The Botswanian Programming Legend masquerading as Mark Gravell on Stack Overflow informed me that the issue was that EF was lazily-loading some portion of the object graph and I needed to force an eager load by use of Entity Framework .Include. HUZZAH!

But I was already forcing an eager load wasn’t I ? See…

summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("Equipments.EquipmentReadingUnits")

Mais Non! I was NOT forcing an eager load because I had improperly specified the path to EquipmentReadingUnits. I had only included the path from about half-way up the object graph I needed to include the full path from the root Entity. Like so:
summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("SubstationGroup.Substations.Equipments.EquipmentReadingUnits")

PROPER HUZZAH! The eager load was correctly specified and ObjectDisposedException was banished!

Moral of the Story:

When getting ObjectDisposedException with Entity Framework make sure you have correctly specified the path for your eager loads. And include them if they are not already present. And then you will no longer see this

System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection