实体框架尝试在向db添加其他对象时创建用户

时间:2016-07-03 12:17:04

标签: asp.net asp.net-mvc entity-framework

我正在尝试创建一个地址,我得到了一个奇怪的例外:

  

无法将值NULL插入“LoweredUserName”列,表'SkiShop.dbo.aspnet_Users';列不允许空值。 INSERT失败。       声明已经终止。

我认为好吧,也许有一个流浪用户已经被创建但没有被投入但是没有,在尝试创建和添加地址之前进行db.saveChanges()调用很顺利!

这是我的代码(使用ASP.NET MVC 2):

var userId = Helpers.CreateAspNetUserFromUser(employee.aspnet_Users, employee.TempPass);
try {
    db.SaveChanges(); //no probs
}
catch (Exception) {

    throw; // doesn't land here
}


if (userId != null) {
    employee.AspNetUserId = (Guid)userId;
    try
    {
        employee.TempPass = null;
        Address address = employee.Address;
        address.CreatedById = employee.CreatedById;
        address.ModifiedById = employee.CreatedById;
        address.DateCreated = employee.DateCreated;
        address.DateModified = employee.DateModified;

        db.Addresses.AddObject(address);
        db.SaveChanges(); //throws exception here

为什么要再次创建用户?如果这是一个错误的错误消息我很困惑,因为地址的外键都没问题,并且地址的所有属性也都可以,并且符合数据库规范。

编辑:以下是创建表语句:

CREATE TABLE [Address] (
    AddressId int primary key identity(1,1) not null,
    Street nvarchar(128) not null,
    HouseNr nvarchar(8) not null,
    PostCode nvarchar(128) null,
    [State] nvarchar(128) not null,
    Country nvarchar(128) not null,
    Telephone nvarchar(128) not null,

    --Relationships & auditing
    CreatedById uniqueidentifier not null,
    ModifiedById uniqueidentifier not null,
    DateCreated datetime not null,
    DateModified datetime not null,

    Constraint fk_address_cb Foreign Key (CreatedById) References Aspnet_Users(UserId),
    Constraint fk_address_mb Foreign Key (ModifiedById) References Aspnet_Users(UserId),
);

CREATE TABLE Employee (
    SvnNr nvarchar(16) primary key not null,
    DOB date not null,

    --Relationships & auditing
    AddressId int not null,
    AspNetUserId uniqueidentifier not null,
    CreatedById uniqueidentifier not null,
    ModifiedById uniqueidentifier not null,
    DateCreated datetime not null,
    DateModified datetime not null,
    TempPass nvarchar(max) null,

    Constraint fk_employee_address Foreign Key (AddressId) References [Address](AddressId),
    Constraint fk_employee_user Foreign Key (AspNetUserId) References Aspnet_Users(UserId),
    Constraint fk_employee_cb Foreign Key (CreatedById) References Aspnet_Users(UserId),
    Constraint fk_employee_mb Foreign Key (ModifiedById) References Aspnet_Users(UserId),
);

1 个答案:

答案 0 :(得分:1)

Why is it trying to create a user again?因为您的数据库设计中有fk_employee_user而EF会反映出来。实例化Employee时,.Net也会为Employee创建一个空用户对象。这些创建的对象只是对象的瞬间,它们的大多数属性都是null。为了避免这种情况,在保存AddressEmployee之前,请执行

之类的操作
  

Employee.User = NULL;

在这种情况下,EF永远不会尝试为Employer保存用户。确保在Employee对象中包含所需的userId。