English 中文(简体)
EF 从父对象中移除子对象
原标题:EF remove child objects from within parent object

我用EF为我的数据库表格提供课程:

public partial class Course
{
    public Course()
    {
        this.People = new HashSet<People>();
    }

    public int ID { get; set; }
    public string Name { get; set; }       

    public virtual ICollection<Person> People { get; private set; }     
}

public partial class Person
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Course Course { get; set; }
}

正如你所看到的,每门课程都有一批人。我创建了第二个部分班,所以当我刷新EF图表时,我的代码不会被清除。我的问题是,我怎样才能从课程对象中清除人员名单?

我试过了:

public partial class Course
{    
      public void ResetCourse()
      {
          this.People.Clear();
      }
}

但我明白这个错误:

操作失败: 无法更改关系, 原因是外钥属性中的一种或多种不可更改。 当更改关系时, 相关的外钥属性被设置为无效值。 如果外钥属性不支持无效值, 必须定义新的关系, 外钥属性必须被指定另一个非无效值, 或者必须删除不相关的对象 。

其原因显然是因为EF实际上没有删除个人对象,而只是删除SQL扔出的两者之间的关系,因为它不能有无效的钥匙。

Apparently i should use something like context.DeleteObject(person)

然而,在课程内,它没有提及上下文,我想将代码保留在对象内,使其简单化为ui代码。

最佳回答

与其使用课程班来管理数据库操作,不如在与实体框架合作时使用存储库和单位工作模式,否则,贵实体总是有其背景;这会导致一些问题。

Just create a Course repository with context as a parameter and employ the database operations in the repository instead of the entity itself. Refer to: Unit of Work and repository patterns

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签