简体   繁体   中英

EF 4.1 One to Many relationship

I have what I consider a very simple data model and I'm struggling badly 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 like this:

public class SiteConfiguration : EntityTypeConfiguration<Site> {

public SiteConfiguration() {
  HasMany(c => c.buildings)
    .WithRequired()
    .HasForeignKey(c => c.siteId);
  }
}

In my controller for MVC I simply want to remove a building from a 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 relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. Any thoughts or suggestions would be greatly appreciated.

Try this:

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 REQUIRES a site, and doesn't make sites worry about building requirements or vice versa.

As I understand it, you only pull in HasMany.WithMany/WithRequired in many-many relationships and the like.

You could try and replace this line:

public int siteId { get; set; }

With this:

public Site site { get; set; }

There are two ways to describe a relationship with the class names or with the id. You combined both that is why you got the relationship already exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM