违反了多重约束。 DB首先是EF 4.1

时间:2012-12-30 07:09:50

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

我有以下型号: EDMX

我运行以下内容添加新用户:

    using (var context = new CamelotDB())
    {
        Console.WriteLine("Creating Test User");
        DomainEntity userToAdd = new DomainEntity()
        {
            EntityName = "Test User",
            EntityType = DomainEntity.eEntityType.User,
            EntityCreationDate = DateTime.Now,
            EntityLastUpdateDate = DateTime.Now,
            EntityCreatorUserID = 0,
            Creator = context.DomainEntities.Find(0),
            EntityUpdaterUserID = 0,
            Updater = context.DomainEntities.Find(0),
            EntityParentID = null,
            UserDetails = new User()
            {
                Username = "TestUser",
                Password = "123",
                Email = "TestUser@Test.org",
                FirstName = "Test",
                LastName = "User",
                Phone = "123456789"
            }
        };

        Console.WriteLine("Adding user to Database...");
        userToAdd = context.DomainEntities.Add(userToAdd);
        context.SaveChanges();

    }

我收到以下错误: 违反了多重约束。关系'CamelotShiftManagement.DAL.DomainEnttyFK1'的'User'角色具有多重性1或0..1。![在此处输入图像描述]

1 个答案:

答案 0 :(得分:1)

问题不在于域实体引用的用户实体。 问题是创建者和更新者的自引用。 它们都不是Nullable ...所以我必须在属性中添加一个实际的ID号,并将实际的User实体放在Creator和Updater的Navigation Properties中。