简体   繁体   English

使用Entity Framework为多个表播种

[英]Seeding many to many tables with Entity Framework

I have a meeting entity and a users entity which have a many to many relationship. 我有一个会议实体和一个具有多对多关系的用户实体。

I'm using Autopoco to create seed data for the Users and meetings How do i seed the UserMeetings linking table that is created by EntityFramework with seed data? 我正在使用Autopoco为用户和会议创建种子数据如何为EntityFramework创建的UserMeetings链接表播种种子数据?

The linking table has two fields in it; 链接表中有两个字段; User_Id, and Meeting_ID. User_Id和Meeting_ID。

I'm looping through the list of users that autopoco creates and attaching a random number of meetings 我正在遍历autopoco创建并附加随机数量的会议的用户列表

Here's what i've got so far. 这是我到目前为止所拥有的。

 foreach (var user in userList)
        {

            var rand = new Random();

            var amountOfMeetingsToAdd = rand.Next(1, 300);

            for (var i = 0; i <= amountOfMeetingsToAdd; i++)
            {
                var randomMeeting = rand.Next(1, MeetingRecords);

                //Error occurs on This line
                user.Meetings.Add(_meetings[randomMeeting]);
            }

        }

I got an 'Object reference not set to an instance of an object.' 我得到了一个'对象引用未设置为对象的实例'。 even though the meeting record that i'm trying to attach does exist. 即使我试图附加的会议记录确实存在。

For info all this is happening prior to me saving the context to the DB. 有关信息,所有这一切都发生在我将上下文保存到数据库之前。

There are 4 things on that line that could theoretically be null that would give you that error: 在该行上有4件事理论上可以为null,这会给你这个错误:

  • user 用户
  • Meetings 会议
  • _meetings _meetings
  • randomMeeting randomMeeting

try putting some if statements in front to check for null values. 尝试在前面放置一些if语句来检查空值。

My guess would be that it is _meetings that is null, but that is just a guess. 我的猜测是_meetings是null,但这只是猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM