EF 4.1 One to Big

I have what I consider to be a very simple data model and I am struggling poorly with EF 4.1 CF.

My data model has two classes:

public class Site { public int id { get; set; } public string name { get; set; } public ICollection<Building> buildings { get; set; } } public class Building { public int id { get; set; } public int siteId { get; set; } public string name { get; set; } } 

My configuration files are as follows:

 public class SiteConfiguration : EntityTypeConfiguration<Site> { public SiteConfiguration() { HasMany(c => c.buildings) .WithRequired() .HasForeignKey(c => c.siteId); } } 

In my controller for MVC, I just want to remove the building from the site. Here is my controller code:

 public ActionResult Delete(int id, int siteId) { var site = repo.GetById(siteId); var building = site.buildings.SingleOrDefault(c => c.id == id); ou.buildings.Remove(site); repo.Save(); } 

My error message:

The operation failed: the relation cannot be changed because one or more properties of the foreign key are nonzero. When a relationship change occurs, the related foreign-key property is null. If the foreign key does not support null values, a new relationship must be defined, a foreign key property must be assigned another non-zero value, or an unrelated object must be deleted. Any thoughts or suggestions are greatly appreciated.

+4
source share
2 answers

Try the following:

 public class Building { public int id { get; set; } public Site Site { get; set; } ... } public class SiteConfiguration : EntityTypeConfiguration<Site> { public SiteConfiguration() { HasMany(c => c.buildings); } } public BuildingConfiguration : EntityTypeConfiguration<Building> { public BuildingConfiguration() { HasRequired(s=>s.Site); } } 

This tells the site that it can have many buildings and tells the building that it is REQUIRED on the site and does not make sites worry about building requirements or vice versa.

As I understand it, you only pull HasMany.WithMany / WithRequired in many ways, etc.

+1
source

You can try and replace this line:

 public int siteId { get; set; } 

Wherein:

 public Site site { get; set; } 

There are two ways to describe relationships with class names or with an identifier. You combined both, so you already got a relationship.

0
source

All Articles