简体   繁体   English

防止在创建具有实体框架关系的其他实体时复制现有对象

[英]Prevent duplication of existing object on creating other entities with entity framework relationship

I have a student who take assessments (1..n) which are made up of tests (1..n) and thus a student takes many tests (also 1..n).我有一个学生参加由测试 (1..n) 组成的评估 (1..n),因此学生参加了许多测试(也是 1..n)。 When I am posting the assessment to the web service I am using a viewmodel which has the student object, (already in the db) attached.当我将评估发布到 Web 服务时,我使用的是附有学生对象(已在数据库中)的视图模型。 I also create a couple of tests which are sent in with the assessment.我还创建了几个测试,这些测试与评估一起发送。 I can see from the debugger that when the assessment arrives at my web service's postassessment method, that it has everything attached including the student.我可以从调试器中看到,当评估到达我的 Web 服务的 postassessment 方法时,它包含了包括学生在内的所有内容。 However, I am getting a 409 duplicate conflict - the debugger says it is a primary key violation cannot enter duplicate.但是,我遇到了 409 重复冲突 - 调试器说这是主键冲突,无法输入重复。 For example, if I give the student a new Guid, then everything works, relationships are created etc, but obviously this creates a new student object.例如,如果我给学生一个新的 Guid,那么一切正常,建立关系等等,但显然这会创建一个新的学生对象。 I want to target the existing student and create the relationships.我想针对现有学生并建立关系。 From reading other questions on SO, (like here and here ) and this article on MSDN , I think it has something to do with the current context not knowing about the existing object and it tried to create it?通过阅读有关 SO 的其他问题(如此此处)以及MSDN上的这篇文章,我认为这与不了解现有对象并尝试创建它的当前上下文有关? I have tried to get the existing student from the db and set the assessment's student to it, attach it, etc but I am not really understanding what is happening here.我试图从数据库中获取现有学生并将评估的学生设置为它,附加它等,但我并没有真正理解这里发生了什么。 Speaking of duplicates, I understand there are various versions of this question on here, but like I said, I am struggling to understand.说到重复,我知道这里有这个问题的各种版本,但就像我说的,我很难理解。

 public async Task<IHttpActionResult> PostAssessment(Assessment item)
    {
        using (var context = new DBContext())
        {
            Student theStudent = context.Students.Single(s => s.Id == item.Student.Id);
            item.Student = theStudent;
            //context.Students.Attach(theStudent);
            context.Entry(theStudent).State = EntityState.Modified;
            context.SaveChanges();
        }
        Assessment current = await InsertAsync(item);
        return CreatedAtRoute("Tables", new { id = current.Id }, current);  
    }

This is wrong.这是错误的。

From your code it is not clear how the other side of the relationship looks but I would think it would look something like (on the student object): theStudent.Assessments?从您的代码中不清楚关系的另一面看起来如何,但我认为它看起来像(在学生对象上):theStudent.Assessments? In that case I would rather add the assessment to the student instead of adding the student to the assessment.在这种情况下,我宁愿将评估添加到学生中,而不是将学生添加到评估中。 eg:例如:

public async Task<IHttpActionResult> PostAssessment(Assessment item)
{
    using (var context = new DBContext())
    {
        Student theStudent = context.Students.Single(s => s.Id == item.Student.Id);
        item.Student = null;//Just to make sure there is not other relationship here
        //because 'theStudent' was retreived from the db it will be in the change graph so any changes will be recoreded
        theStudent.Assessments.add(item);//I am assuming it should be added because it is a POST method   
        context.SaveChanges();
    }
    Assessment current = await InsertAsync(item);
    return CreatedAtRoute("Tables", new { id = current.Id }, current);  
}

The other option you have it to just insert the assignments and just maintain the StudentId on the assignment (if the model was set up correctly the Assessment object should have a StudentId property as well as a Student Property) eg:另一个选项是插入作业并仅在作业中维护 StudentId(如果模型设置正确,Assessment 对象应该具有 StudentId 属性和 Student 属性)例如:

public async Task<IHttpActionResult> PostAssessment(Assessment item)
{
    using (var context = new DBContext())
    {
        Student theStudent = context.Students.Single(s => s.Id == item.Student.Id);
        item.StudentId = item.Student.Id;
        item.Student = null;   
        //context.Students.Attach(theStudent);
        context.Assemssments.Add(item);
        context.SaveChanges();
    }
    Assessment current = await InsertAsync(item);
    return CreatedAtRoute("Tables", new { id = current.Id }, current);  
}

Hope this is what yoy were looking for.希望这是 yoy 正在寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架代码首先与现有实体进行多对多关系 - Entity Framework Code First Many to Many Relationship with Existing Entities 使用带有现有子实体的实体框架在数据库中创建实体时出现问题 - Problem creating an entity in the database using Entity Framework with existing child entities 实体框架创建与现有实体关系的新实体,导致尝试创建现有实体的新副本 - Entity Framework creating new entity with relationship to existing entity, results in attempt to create new copy of the existing entity 实体框架:*中的实体参与*关系 - Entity Framework: Entities in * participate in the * relationship 使用partial类扩展Entity framework 5实体并将其映射到现有的其他实体 - Extend Entity framework 5 entity using partial class and map it to existing other entities 在Entity Framework Core中删除实体之间的关系 - Delete relationship between entities in Entity Framework Core 实体框架中多对多关系中的多个实体 - Mutiple entities in a many to many relationship in Entity Framework 具有实体框架的实体之间的复杂关系 - Complex relationship between entities with Entity Framework 对实体框架中的现有实体进行更改 - Making changes to existing entities in Entity Framework 阻止实体框架自动附加实体 - Prevent Entity Framework to automatically attach entities
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM