首页 > 解决方案 > 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 的实体。我首先使用实体​​框架代码创建了我的数据库。这两个表之间存在一对多的关系。问题是当我向文章表插入操作时,我从会话添加到模型用户实体并在我的用户表上插入了重复的输入,因为我之前已经插入了我的用户。

我应该怎么做才能解决?

标签: databaseentity-frameworkef-code-firstcode-firstrelational

解决方案


   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();
        }
    }

推荐阅读