实体框架 - 数据库优先 - 违反多重约束,关系Y的角色X具有多重性1或0..1

时间:2017-03-31 04:17:03

标签: c# winforms entity-framework-6

首先使用DB(EF 6),我创建了1个父亲 - 2子关系。 Student_Temp是父对象,并标记为具有1或0..1关系的子项。

Student_Temp.cs如下:

using System;
using System.Collections.Generic;

public partial class Student_Temp
{
    public Student_Temp()
    {
        this.Marks = new HashSet<Mark>();
    }

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

    public virtual ICollection<Mark> Marks { get; set; }
}

Mark.cs如下:

using System;
using System.Collections.Generic;

public partial class Mark
{
    public int Id { get; set; }
    public string SubjectName { get; set; }
    public Nullable<int> Marks { get; set; }
    public int StudentId { get; set; }

    public virtual Student_Temp Student_Temp { get; set; }
}

更新代码如下:

using (DBContext = new SampleEntities1())
            {
                student_Temp = DBContext.Student_Temp.Include(T => T.Marks).FirstOrDefault(S => S.StudentId == selectedStudentId);

                student_Temp.Name = txtName.Text;

                student_Temp.Marks.Clear();
                student_Temp.Marks = mark;

                foreach (var TP in student_Temp.Marks.ToList())
                {
                    if (TP.Id > 0)
                    {
                        Mark M = student_Temp.Marks.FirstOrDefault(T => T.Id == TP.Id);

                        M.Marks = Convert.ToInt32(txtMarks.Text);
                    }
                    else
                    {
                        //student_Temp.Marks.Add(TP);
                        DBContext.Marks.Add(TP);
                    }
                }

                DBContext.SaveChanges();
            }

在更新现有学生记录时,如果我在Mark集合中添加新记录,那么我将收到上述错误。我用Google搜索了这么多,但找不到合适的解决方案。

0 个答案:

没有答案