EF 保存数据时,如果数据存在外键,则保存出错解决

下面时错误情况

如果外键对象  主键自增的话,那么EF会自动修改主键,然后自增存入DB,不会报错

如果主键改为不自增的话,那么保存的时候就会报错

var greadInfo = new GreadInfo() { id = 5, number = "04", createTime = new DateTime(1878, 8, 4), master = "asdfwer" };
using (CodeFirstDBContext dbContext = new CodeFirstDBContext())
            {
                
          
                try
                {
                    
                        var s = new Student()
                        {
                            name = "hjery",
                            number = "6795",
                            age = 56,
                            birthday = new DateTime(1854, 2, 5),
                            GreadInfo = greadInfo
                        };
                    var s2 = new Student()
                    {
                        name = "uyhjkfgjh",
                        number = "7689",
                        age = 43,
                        birthday = new DateTime(1896, 12, 25),
                        GreadInfo = greadInfo
                    };
                    List<Student> list = new List<Student>();
                    list.Add(s);
                    list.Add(s2);
                    // 写数据库
                    dbContext.Student.AddRange(list);
                    var i = dbContext.SaveChanges();
                    Console.WriteLine(i);
                }
                catch (DbEntityValidationException dbEx)
                {
                    Console.WriteLine(dbEx);
                }
                
            }

 

正确的情况    外键使用上下文对象

 using (CodeFirstDBContext dbContext = new CodeFirstDBContext())
            {
                
          
                try
                {
                    var greadInfo = dbContext.GreadInfo.Find(5);//根据主键查询,如果主键是多个,那么就写多个参数,按照主键顺序

                        var s = new Student()
                        {
                            name = "hjery",
                            number = "6795",
                            age = 56,
                            birthday = new DateTime(1854, 2, 5),
                            GreadInfo = greadInfo
                        };
                    var s2 = new Student()
                    {
                        name = "uyhjkfgjh",
                        number = "7689",
                        age = 43,
                        birthday = new DateTime(1896, 12, 25),
                        GreadInfo = greadInfo
                    };
                    List<Student> list = new List<Student>();
                    list.Add(s);
                    list.Add(s2);
                    // 写数据库
                    dbContext.Student.AddRange(list);
                    var i = dbContext.SaveChanges();
                    Console.WriteLine(i);
                }
                catch (DbEntityValidationException dbEx)
                {
                    Console.WriteLine(dbEx);
                }
                
            }

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页