我的数据模型有两个类:
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# – EF 4.1一对多关系全部内容,希望文章能够帮你解决c# – EF 4.1一对多关系所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)