1

我有休闲模特

namespace Prometheus.Models
{
    [Table("People")]
    public class Person : IPerson
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Name
        {
            get
            {
                return FirstName + " " + LastName;
            }
            set{}
        }

        public string Email { get; set; }
        public DateTime? LastModified { get; set; }
    }
}

一个继承它的人

namespace Prometheus.Models
{
    [Table("UserProfile")]
    public class UserProfile : Person
    {
        public string UserName { get; set; }
        public string CNP { get; set; }
        public virtual Faculty Faculty { get; set; }
        public bool? IsUSAMV { get; set; }
        public virtual ICollection<Result> Results { get; set; }
        public virtual ICollection<Project> Projects { get; set; }
    }
}

和种子方法

private void AddUser(string user, string password,
    SimpleMembershipProvider membership)
{
    if (membership.GetUser(user, false) == null)
    {
        WebSecurity.CreateUserAndAccount(user, password, new
        {
            CNP = "1890531111111",
            IsUSAMV = true,
        });
    }
}

当我尝试在没有 UserProfile 扩展 Person 的情况下运行种子方法时,一切都很好,但是当它扩展它时,我不断收到休闲错误。

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UserProfile_dbo.People_Id". The conflict occurred in database "PrometheusDb", table "dbo.People", column 'Id'.
The statement has been terminated.

任何帮助将不胜感激,谢谢。

我尝试将我的功能更新为

private void AddUser(string firstName,string lastName, string password,
    SimpleMembershipProvider membership)
{
    var user = firstName + "." + lastName;
    if (membership.GetUser(user, false) == null)
    {
        var profile = new UserProfile()
        {
            Email = "test@email.com",
            FirstName = firstName,
            LastName = lastName
        };
        _context.Users.Add(profile);
        _context.SaveChanges();
        WebSecurity.CreateAccount(user, password);
    }
}

但现在我得到: -更新条目时发生错误。有关详细信息,请参阅内部异常。System.Data.SqlClient.SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“UserProfile”中插入标识列的显式值。

4

1 回答 1

2

您在创建项目的顺序和数据库上的完整性检查方面遇到问题。我做过类似的事情,它涉及先保存用户然后保存帐户。我的代码如下所示:

var user = new User { UserName = model.UserName, Organisation = userOrg };
this.repository.SaveUser(user);
string token = WebSecurity.CreateAccount(model.UserName, model.Password, true);

注意使用CreateAccount而不是CreateUserAndAccount方法

于 2013-11-12T16:38:02.100 回答