database - EntityFramework 一对多关系重复插入问题
问题描述
enter code here
[Table("Articles")]
public class Article : IEntity
{
[Required, StringLength(60)]
public string Title { get; set; }
public int CategoryId { get; set; }
[Required, StringLength(2500)]
public string Text { get; set; }
public int LinkCount { get; set; }
public virtual User Owner { get; set; }
public virtual Category Category { get; set; }
public virtual Html_Content_Result HtmlPage { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual List<Liked> Likes { get; set; }
}
[Table("Users")]
public class User : IEntity
{
[StringLength(25)]
public string Name { get; set; }
[StringLength(25)]
public string Lastname { get; set; }
[StringLength(25), Required]
public string Username { get; set; }
[StringLength(100), Required]
public string Password { get; set; }
[StringLength(70), Required]
public string Email { get; set; }
public bool IsActive { get; set; }
[Required]
public Guid ActivateGuid { get; set; }
public virtual List<Article> Articles { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual List<UsersRole> UsersRoles { get; set; }
public virtual List<Liked> Likes { get; set; }
}
我有两个名为 User 和命名 Article 的实体。我首先使用实体框架代码创建了我的数据库。这两个表之间存在一对多的关系。问题是当我向文章表插入操作时,我从会话添加到模型用户实体并在我的用户表上插入了重复的输入,因为我之前已经插入了我的用户。
我应该怎么做才能解决?
解决方案
public int Add(TEntity entity)
{
if (entity is IEntity)
{
IEntity myEntity = entity as IEntity;
DateTime dateTime = DateTime.Now;
myEntity.CreatedOn = dateTime;
myEntity.ModifiedOn = dateTime;
myEntity.ModifiedUsername = identity.Id.ToString();
}
using (TContext context = new TContext())
{
context.Configuration.LazyLoadingEnabled = false;
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
return context.SaveChanges();
}
}
推荐阅读
- python - Linkedin 分页抓取工作
- javascript - 如何中止提交
- javascript - JavaScript async/await 和同步 JavaScript 有什么区别?
- javascript - 引导导航栏下拉菜单不起作用,而是在按下时刷新页面
- javascript - 在 Jest 中添加测试用例如何降低代码覆盖率?
- bash - 在本地使用函数来检查空白字符串
- string - 如何检查字符串是否只包含字母、数字、下划线和句点。颤振/飞镖
- mysql - 从 MySQL 中的 JSON 数组中删除
- arrays - 使两个数组等效的最佳方法
- ruby-on-rails - 解析时.yaml文件语法错误找不到问题