我首先使用模型。
实体:
class User
{
Guid UserId{get;set;}
Guid RefererUserId {get;set;}
User RefereUser {get;set;}
}
数据上下文:
public class DataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasRequired(x => x.ReferrerUser)
.WithMany()
.HasForeignKey(x => x.ReferrerUserId).WillCascadeOnDelete(false);
}
public DbSet<User> Users { get; set; }
}
我初始化数据库:
MembershipCreateStatus Status;
Membership.CreateUser("Demo", "123456", "demo@demo.com", null, null, true, out Status);
Roles.CreateRole("Admin");
Roles.AddUserToRole("Demo", "Admin");
DataContext db = new DataContext();
var a = db.Users.Where(x => x.Email == "demo@demo.com").FirstOrDefault();
a.MoneyRUB = 100;
a.MoneyUSD = 100;
db.SaveChanges();
我得到错误:
INSERT 语句与 FOREIGN KEY SAME TABLE 约束“User_ReferrerUser”冲突。冲突发生在数据库“Kamikaze”、表“dbo.Users”、列“UserId”中。该语句已终止。
我究竟做错了什么?