加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – EF 4.1一对多关系

发布时间:2020-12-15 21:20:19 所属栏目:百科 来源:网络整理
导读:我有一个非常简单的数据模型,而且我在使用EF 4.1 CF时遇到了很多困难. 我的数据模型有两个类: public class Site { public int id { get; set; } public string name { get; set; } public ICollectionBuilding buildings { get; set; }}public class Build
我有一个非常简单的数据模型,而且我在使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读