c# – EF 4.1一对多关系
作者:互联网
我有一个非常简单的数据模型,而且我在使用EF 4.1 CF时遇到了很多困难.
我的数据模型有两个类:
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; }
}
我的配置文件是这样的:
public class SiteConfiguration : EntityTypeConfiguration<Site> {
public SiteConfiguration() {
HasMany(c => c.buildings)
.WithRequired()
.HasForeignKey(c => c.siteId);
}
}
在我的MVC控制器中,我只想从一个站点中删除一个建筑物.这是我的控制器代码:
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();
}
我的错误信息:
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.
解决方法:
试试这个:
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);
}
}
这告诉站点它可以有许多建筑物,并告诉建筑物它需要一个站点,并且不会让站点担心建立需求,反之亦然.
据我所知,你只在许多关系等中引入HasMany.WithMany / WithRequired.
标签:c,entity-framework,code-first 来源: https://codeday.me/bug/20190710/1419270.html