如何将值插入虚拟字段

时间:2015-08-29 22:49:45

标签: c# sql-server entity-framework asp.net-mvc-5

我有一个学习者表,我在用户注册时设置值,'注册(RegisterViewModel模型)'在AccountController中。

 if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);


                using (The_FactoryDBContext db = new The_FactoryDBContext())
                    {
                        Learner learner = new Learner();

                        learner.learnerID = User.Identity.GetUserId();
                        learner.llCounter = 0;
                        learner.dtwCounter = 0;
                        learner.ftwCounter = 0;
                        learner.counter = 0;

                        db.Learners.Add(learner);
                        db.SaveChanges();
                    }
                }
       }

这是我的学习者自动生成的类看起来与一些虚拟字段的对比。

public partial class Learner
{
    public Learner()
    {
        this.Learner_Treasure = new HashSet<Learner_Treasure>();
    }

    public string learnerID { get; set; }
    public int llCounter { get; set; }
    public int dtwCounter { get; set; }
    public int ftwCounter { get; set; }
    public int counter { get; set; }

    public virtual AspNetUser AspNetUser { get; set; }
    public virtual ICollection<Learner_Treasure> Learner_Treasure { get; set; }
}

}

然而,我在注册时遇到此错误,我不知道如何修复它,有人可以帮助我,或者我的代码可能在错误的地方?

  

INSERT语句与FOREIGN KEY约束冲突&#34; FK_Learner_AspNetUsers1&#34;。冲突发生在数据库&#34; The_Factory&#34;,table&#34; dbo.AspNetUsers&#34;,column&#39; Id&#39;。

AspNetUser类

public partial class AspNetUser
{
    public AspNetUser()
    {
        this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
        this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
        this.AspNetRoles = new HashSet<AspNetRole>();
    }

    public string Id { get; set; }
    public string Email { get; set; }
    public bool EmailConfirmed { get; set; }
    public string PasswordHash { get; set; }
    public string SecurityStamp { get; set; }
    public string PhoneNumber { get; set; }
    public bool PhoneNumberConfirmed { get; set; }
    public bool TwoFactorEnabled { get; set; }
    public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
    public bool LockoutEnabled { get; set; }
    public int AccessFailedCount { get; set; }
    public string UserName { get; set; }
    public int AvatarID { get; set; }

    public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
    public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
    public virtual Avatar Avatar { get; set; }

    public virtual Learner Learner { get; set; }
    public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}

}

1 个答案:

答案 0 :(得分:0)

尝试

[ForeignKey("AspNetUser")]

超过learnerID财产。原因是EF不知道您正在创建从learneruser的1-1映射(并且learner中的PK也是user的FK )。放置此属性将告诉EF您的设计。