[英]Code-First: Null reference exception when adding an entity to a dbset
I have a very simple database with 2 tables: Test and Tester, Test has an Id and a Name, Tester has an Id a TestName and a TestId. 我有一个非常简单的数据库,有2个表:Test和Tester,Test有一个Id和一个Name,Tester有一个Id a TestName和一个TestId。 There is a 1 : N connection between the two.
两者之间有1:N的连接。 What I simply like to do is add a new entry to one of the tables but I got a null reference exception.
我只想做的是在其中一个表中添加一个新条目,但是我得到了一个空引用异常。
I have a class for the context: 我有一个上下文的类:
public class TestContext : DbContext, ITestContext
{
public DbSet<Test> Tests { get; set; }
public DbSet<Tester> Testers { get; set; }
public TestContext()
: base(){}
public TestContext(DbConnection connection) : base (connection, false)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TestConfiguration());
modelBuilder.Configurations.Add(new TesterConfiguration());
}
}
The two configuration files contains the relations and some restrictions. 这两个配置文件包含关系和一些限制。
And I have an EntityManager class that can add a new entity to one the objects: 我有一个EntityManager类,可以向对象添加一个新实体:
private ITestContext _context;
public ObservableCollection<Test> Tests { get; set; }
public ObservableCollection<Tester> Testers { get; set; }
private static EntityManager _instance;
public static EntityManager Instance
{
get { return _instance ?? (_instance = new EntityManager()); }
}
private EntityManager()
{
Tests = new ObservableCollection<Test>();
Testers = new ObservableCollection<Tester>();
Database.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlClient");
connection = Database.DefaultConnectionFactory.CreateConnection(@"Data Source=.;Initial Catalog=Test;Integrated Security=True");
_context = new TestContext(connection);
_context.Tests.Add(new Test {Name = "new Test"});
_context.SaveChanges();
LoadData();
}
private void LoadData()
{
Tests.Clear();
Testers.Clear();
_context.Tests.ToList().ForEach(Tests.Add);
_context.Testers.ToList().ForEach(Testers.Add);
}
So when I try to add the "new test" to the tests I got a null reference exception. 因此,当我尝试将“新测试”添加到测试时,我得到了一个空引用异常。 And if I leave the add part out it runs perfectly but then I lost the functionalty to add a new entity to a collection.
如果我离开添加部分它运行完美,但后来我失去了向集合中添加新实体的功能。 Could someone advise me what could go wrong?
有人可以告诉我什么可能出错吗? Cheers!
干杯!
There was a problem in the models, and the configurations. 模型和配置存在问题。 Wrong connection between the tables.
表之间的连接错误。
Hopefully this will help someone... 希望这会帮助某人......
I've ran into a similar problem, having a NullReferenceException on DbSet.Add and the funny part was that it only happened once for each DbSet called in the controller action. 我遇到了类似的问题,在DbSet.Add上有一个NullReferenceException,而有趣的部分是它只发生在控制器动作中调用的每个DbSet一次。 There were three, so after three repeated requests the code succeeded.
有三个,所以经过三次重复请求后代码成功了。
REASON: I invoked an async DB read before calling Add and only awaited it at the end. 原因:我在调用Add之前调用了异步数据库读取,并且最后只等待它。 When I moved the await in front of these calls, the issue was gone.
当我在这些电话前移动await时,问题就消失了。
This will cause the problem 这将导致问题
var task = UserManager.FindByIdAsync(User.Identity.GetUserId()); // Uses the same DB Context
DbContext.Stages.Add(...);
await task;
Okay. 好的。 I ran into this issue as well.
我也遇到过这个问题。 For me, it was because I had a WPF application that was attempting to read my EntityState in one of its ICommands while my Entity was being modified by an event trigger.
对我来说,这是因为我有一个WPF应用程序试图在我的实体被一个事件触发器修改时,在其ICommands中读取我的EntityState。 Not sure why this was an issue, as I saw that everything was on the same Dispatcher thread, but by using
不知道为什么这是一个问题,因为我看到一切都在同一个Dispatcher线程上,但通过使用
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => MyEntity.MyEntityProperty=SomeValue));
for the code that was in my event, I was able to solve my problem. 对于我活动中的代码,我能够解决我的问题。
Hopefully this helps someone else. 希望这有助于其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.