ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – EF 4.1一对多关系

2019-07-10 02:09:02  阅读:156  来源: 互联网

标签:c entity-framework code-first


我有一个非常简单的数据模型,而且我在使用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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有