与WillCascadeOnDelete进行单向关联 [英] Unidirectional association with WillCascadeOnDelete

查看:138
本文介绍了与WillCascadeOnDelete进行单向关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的单向类映射。

  public class MyDbContext:DbContext 
{
public MyDbContext():base(CodeFirstDatabase b $ b {

}

public DbSet< Contact>联系人{get;组; }
public DbSet< PhoneNumber>数字{get;组;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove< PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove< IncludeMetadataConvention>();
modelBuilder.Entity< Contact>()
.HasMany(c => c.Numbers)
.WithOptional()
//.Map(p => p。 MapKey(ContactId))
.WillCascadeOnDelete(true);
}
}

如您所见,Contact有一个数字列表,但是Number不了解任何关于联系的内容(它没有属性为父)。
我想在这里做的是实现以下内容:
当数字从联系人中删除并使用SaveChanges保存时,我希望该数字行从数据库中删除,而EF设置外键为空,该行仍保留在数据库中。任何想法怎么了?



谢谢。

解决方案

但是EF不提供任何方式自动删除孤儿。



您必须手动删除 PhoneNumber 实例(即 context.Number.Remove(theNumber)


I have a very simple unidirectional class mappings.

public class MyDbContext : DbContext
{
    public MyDbContext() : base("CodeFirstDatabase")
    {

    }

    public DbSet<Contact> Contacts { get; set; }
    public DbSet<PhoneNumber> Number { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Entity<Contact>()
            .HasMany(c => c.Numbers)
            .WithOptional()
            //.Map(p => p.MapKey("ContactId"))
            .WillCascadeOnDelete(true);
    }
}

As you can see, Contact has a list of Numbers, but Number doesn't know anything about contact (it doesn't have a property on it's parent). What I'm trying to do here is to achieve the following: when number is removed from contact and saved using SaveChanges, I want that number row to be removed from database, but instead, EF sets the foreign key to null and the row remains in database. Any idea what's wrong?

Thanks.

解决方案

It's annoying, but EF does not offer any way to automatically delete orphans.

You have to manually delete the PhoneNumber instances (i.e. context.Number.Remove(theNumber).

这篇关于与WillCascadeOnDelete进行单向关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆