public class DBUser
{
public int Id { get; set; }
public string Family { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public string Position { get; set; }
public int? factoryID { get; set; }
public DbFactoryModel Factory { get; set; }
public ICollection<DbContactsModel> UserContacts { get; set; }
}
public class DbFactoryModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Address { get; set; }
public string Phones { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public virtual ICollection<DbUserModel> _Employees { get; set; }
}
插入新用户的方法:
public int AddUser(int factoryId, DbUserModel model, List<DbContactsModel> userContacts)
{
if (model == null) return 0;
using (var context = new PLContext())
{
int c = context.Users.ToList().Where(fk => fk.Family.Contains(model.Family)
&& fk.FirstName.Contains(model.FirstName)
&& fk.LastName.Contains(model.LastName)
).Count();
if (c == 0)
{
context.Users.Attach(model);
context.Entry(model).State = EntityState.Added;
}
else
MessageBox.Show("Сотрудник уже есть в базе");
if (factoryId != 0 && factoryId != -1)
{
var factory = context.Factories.FirstOrDefault(f => f.Id == factoryId);
factory._Employees.Add(model);
}
context.SaveChanges();
if (userContacts.Count() != 0)
{
var index = context.Entry(model).CurrentValues.GetValue<int>("Id");
var user = context.Users.FirstOrDefault(fk => fk.Id == index);
foreach (var item in userContacts)
{
context.Contacts.Attach(item);
context.Entry(item).State = EntityState.Added;
user.UserContacts.Add(item);
}
}
return context.SaveChanges();
}
}
执行后,一切正常,直到user.UserContacts.Add(item);
我不明白为什么他添加了工人,但没有联系人。抛出
System.NullReferenceException:“对象引用不指向对象的实例。”