EF - 通过导航属性将数据保存到数据库 [英] EF - Saving data to DB through Navigation Properties

查看:360
本文介绍了EF - 通过导航属性将数据保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,希望你能帮忙。
我尝试保存我的数据到我的数据库,它有多个表,我想通过我的
导航属性到达他们。但是当我尝试保存数据时,我得到空引用异常(它说我的对象引用没有为任何对象设置 - 我希望我写得很好,我的VS把它当作匈牙利语)。
我尝试了两种不同的方式。



...



.cs: p>

  Mentett mentett = new Mentett(); //通过mentett到达Mentett表
KiesoIdo kiesoido = new KiesoIdo();

当我收到一个null引用异常时,它表示我的对象引用没有设置任何目的。当我第一次尝试时,它说同样的,有时插入语句与外键冲突,我甚至没有在内部异常中使用。我不明白有什么问题请帮助我:(

解决方案

我不认为这是一个实体框架错误
否则你会得到一个ValidationError
它更可能是你的一个属性对象没有初始化,
你得到一个NullReferenceException与
对象引用未设置一个对象的一个​​实例。



例如KiesoIdo初始化?
尝试放在

  Mentett mentett = new Mentett(); 

以下行:

  mentett.KiesoIdo = new KiesoIdo(); 

要分析验证错误,请在您的SaveAllChanges()

之间添加一个try-catch语句
{...}
catch(DbEntityValidationException异常)
{
foreach(DbEntityValidationResult validationErrors in exception.EntityValidationErrors)
{
foreach(DbV alidationError validationError in validationErrors.ValidationErrors)
{
string log = string.Format({0} - {1},
validationError.PropertyName,validationError.ErrorMessage);
}
}
}


I am a little confused,I hope you can help. I try to save my data into my database,which has multiple tables and I wanna reach them through my navigation properties.But when i try to save the data,I get null reference exception (It says my object reference didn't set for any object - I hope I wrote it well,my VS threw it as hungarian). I tried it on 2 different ways.

...

.cs:

        Mentett mentett = new Mentett(); //reaching Mentett table through mentett
        KiesoIdo kiesoido= new KiesoIdo();

When I do I get a null reference exception,It says my object reference didn't set for any object. When I do my 1st try,It says the same and sometimes the Insert statement conflicts with a foreign key I didn't even use in the Inner Exception. I can't understand What is wrong,please help me :(

解决方案

I don't think that this is an Entity Framework error. Else you would get a ValidationError. it is more likely, that one of your property objects is not initialized and you get a NullReferenceException with "Object reference not set to an instance of an object."

E.g. is KiesoIdo initialialized? Try to put under the line

Mentett mentett = new Mentett(); 

the following line:

mentett.KiesoIdo = new KiesoIdo();

To analyze the validation errors, add a try-catch statement around your SaveAllChanges()

try
{ ... }
catch (DbEntityValidationException exception)
{
  foreach (DbEntityValidationResult validationErrors in exception.EntityValidationErrors)
  {
    foreach (DbValidationError validationError in validationErrors.ValidationErrors)
    {
      string log = string.Format("{0} - {1}",
      validationError.PropertyName, validationError.ErrorMessage);
    }
  }
}

这篇关于EF - 通过导航属性将数据保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆