C# 实体框架-插入到列中会创建重复
我使用的是EF6.1.3。基本上我有两门课:C# 实体框架-插入到列中会创建重复,c#,entity-framework,C#,Entity Framework,我使用的是EF6.1.3。基本上我有两门课: public class User { public int Id { get; set; } } public class Card { public int Id { get; set; } public string Name { get; set; } public User CreatedBy { get; set; } } 当然,检查表定义时,会在卡的CreatedBy和用户的Id之间创建外键关系卡片现
public class User
{
public int Id { get; set; }
}
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
public User CreatedBy { get; set; }
}
当然,检查表定义时,会在卡的CreatedBy
和用户的Id
之间创建外键关系<代码>卡片
现在有一个CreatedBy_Id
列用于此
我植入了一个默认的用户
(Id=1),它存储在一个变量中,我们称之为当前用户
。现在,当我想输入一张卡时:
context.Cards.Add(new Card
{
Name = "Card of Water",
CreatedBy = CurrentUser
});
context.SaveChanges();
我得到的结果是创建了新的卡
,但是CreatedBy
没有存储CurrentUser
引用。相反,创建了一个新的用户
(Id=2),这就是存储在新卡
中的由
创建的内容
我怎样才能纠正这个问题?谢谢
编辑:
CurrentUser
在启动窗体的Load
事件中,在程序启动时设置一个值。它被声明为全局变量:
CurrentUser = context.Users.First(); //In load event
添加只是为了测试,真的,在一个按钮中。上面的代码就是它的全部。要解决此问题,您需要在这两个表之间建立外键关系,如下所示:
public class User
{
public int Id { get; set; }
}
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("CreatedBy")]
public int UserId { get; set; }
public User CreatedBy { get; set; }
}
context.Cards.Add(new Card
{
Name = "Card of Water",
UserId = CurrentUser.Id,
CreatedBy = CurrentUser
});
context.SaveChanges();
public class User
{
[Key]
public int Id { get; set; } // primary key
}
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("CreatedBy")]
public int UserId { get; set; } // Foreign Key
public virtual User CreatedBy { get; set; }
//use virtual keyword to allow lazy loading while execution
}
context.Cards.Add(new Card
{
Name = "Card of Water",
UserId = CurrentUser.Id
//No need to insert CreatedBy user object here as we are passing UserId
});
context.SaveChanges();
CurrentUser
变量来自何处?在这里发布完整的代码,我会帮你解决。在dbI中不创建关系在这里可能是错误的,但是既然User
有一个int类型的id,你的Card
类不应该有一个名为public int CreatedById{get;set;}
的变量吗,哪个存储了创建它的用户的实际整数ID?@JenishRabadiya在回答您的问题时,CurrentUser
是在程序启动时设置的,是沿着CurrentUser=context.Users.First()设置的。context.Cards.Add()
@AwonDanag在问题中发布完整代码并更新,我如何才能获得ForeignKey
属性?@JenishRabadiya不是必需的?为什么呢您能解释一下吗?@AwonDanag Entityframework在您分配相关实体(如CreatedBy=CurrentUser
)时会处理它,但CurrentUser在引用上应该与您创建的实例相等。这就是我请你对这个问题发表评论的原因。您如何初始化CurrentUser
并在context.Cards.Add(新卡…..