微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐