【发布时间】:2019-09-10 16:00:44
【问题描述】:
我正在将一个集合添加到现有的数据集中。我有一个学生,其科目仍然是null。所以我正在做的是将post 收藏到那个学生中。
这是我的code:
[HttpPost("{id}/subjects")]
public async Task<ActionResult<object>> PostStudentSubject(string id, Subject item)
{
// this is to get whole subject model using id
Subject subj = await _context.Subjects.FindAsync(item.Id);
// this is to get student model through the given id in parameter
Student stud = await _context.FirstOrDefaultAsync(p => p.Id == id);
if (stud == null){
return NotFound();
}
// this is to remove the "subj" to avoid an Exception:
// "The property 'Id' is part of the object's key information and cannot be modified"
_context.Subjects.Remove(subj);
await _context.SaveChangesAsync();
// and this is now to add a new object Subject to the
// collection of subjects in the student
stud.Subjects.Add(new Subject { Id = subj.Id });
// some subject properties are omitted...
await _context.SaveChangesAsync();
return Ok(stud);
}
它返回 OK 但 Swagger 响应返回这些:
服务器响应
代码 -> 未记录,详细信息 -> 错误:OK
回复
代码 -> 200,描述 -> 成功
可见的问题是主题的ID会变成学生的ID。为什么会这样?我在哪一部分得到这个?
主题
public class Subject
{
[Key]
public string Id { get; set; }
// some codes omitted ...
[ForeignKey("Id")]
public Student student {get; set;}
}
学生
public class Student
{
[Key]
public string Id { get; set; }
// some codes omitted ...
public IList<Subject> Subjects {get; set;} = new List<Subject>();
}
【问题讨论】:
-
您能否为您的学生和学科映射以及实体定义包括任何映射/配置?这听起来好像您的主题被配置为与学生的一对一。或者 FK 映射配置错误。
-
@StevePy 我已经添加了
-
外键属性是你的问题。在代码示例的解决方案中避免了这一点......
标签: c# entity-framework asp.net-web-api