EF 6.1.3 - 无法在对象

时间:2015-10-28 14:43:12

标签: asp.net entity-framework entity-framework-6

我在网站上搜索解决了我的问题,但我仍然没有解决它。 我有2个实体:

public class Article
{
    [Key]
    public Guid ID { get; set; }
    public Guid? ApprovedBy_ID { get; set; }
    public Guid CreatedBy_ID { get; set; }
    public virtual Profile ApprovedBy { get; set; }
    public virtual Profile CreatedBy { get; set; }
    //New guid for new article
    public Article()
    {
        ID = Guid.NewGuid();
    }
}
public class Profile
{
    [Key]
    public Guid ID { get; set; }
    [Required]
    [StringLength(100)]
    public string FullName { get; set; }
    public Profile()
    {
        ID = Guid.NewGuid();
    }
}

这是我的插入逻辑:

    private readonly iContext context;
    public ArticleLogic()
    {
        context = new iContext();
    }
    public IEnumerable<Article> GetAllArticle()
    {
        return context.Articles.Include("Categories").Include("Pictures").Include("ApprovedBy").Include("CreatedBy").Include("Template");
    }

    public Article AddArticle(Article article)
    {
            try
            {
                Profile pf = context.Profiles.First();
                context.Profiles.Attach(pf);

                Article art = new Article();
                art.Title = article.Title;
                art.Description = article.Description;
                art.Content = article.Content;
                art.Tag = article.Tag;
                art.Template = article.Template;
                //pf has ID = '0816f19c-31c1-4103-8f51-ba422beab1c0' (first row in database)
                art.CreatedBy = pf;
                art.CreatedBy_ID = pf.ID;
                context.Articles.Add(art);
                context.SaveChanges();

                return article;
            }
            catch (Exception ex)
            {
                //But ex throw error duplicate ID = '7aa1d064-54ff-47b9-807d-db422fa71f8c' (second row in database)
                Debug.WriteLine(ex.StackTrace);

                throw ex;
            }

    }

数据库上下文:

public myContext()
    : base("name=abc")
{
    this.Configuration.LazyLoadingEnabled = true;
    this.Configuration.ProxyCreationEnabled = false;
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Template> Templates { get; set; }
public virtual DbSet<Article> Articles { get; set; }
public virtual DbSet<Picture> Pictures { get; set; }
public virtual DbSet<Profile> Profiles { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //One-to-many: Article - Picture (nullable)
    modelBuilder.Entity<Picture>()
        .HasOptional<Article>(c => c.Article)
        .WithMany(p => p.Pictures)
        .HasForeignKey(f => f.ArticleId);

    ////One-to-many: Role - Profile
    modelBuilder.Entity<Profile>()
        .HasRequired<Role>(i => i.Role)
        .WithMany(i => i.Profiles)
        .HasForeignKey(f => f.RoleID);

    ///Many-to-many: Article - Category
    modelBuilder.Entity<Article>()
        .HasMany(t => t.Categories)
        .WithMany(t => t.Articles)
        .Map(m => {
                m.ToTable("ArticleCategories");
                m.MapLeftKey("ArticleId");
                m.MapRightKey("CategoryId");
         });
    //
        modelBuilder.Entity<Article>()
            .HasOptional(a => a.ApprovedBy)
            .WithMany(a => a.ArticleApprovedBy)
            .HasForeignKey(f=>f.ApprovedBy_ID)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Article>()
            .HasRequired(a => a.CreatedBy)
            .WithMany(a => a.ArticleCreatedBy)
            .HasForeignKey(f => f.CreatedBy_ID)
            .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
}

我正在使用CodeFirst EF 6.1.3并且收到错误:违反PRIMARY KEY约束'PK_Profiles'。无法在对象'dbo.Profiles'中插入重复键,如此链接Entity Framework Code First - Cannot insert duplicate key in object 'dbo.T_CRProviders'? 谁能帮我?感谢。

3 个答案:

答案 0 :(得分:0)

context认为pf是新的,应该插入到数据库中。显示context的实例化和配置 - 您是否禁用了更改跟踪?

答案 1 :(得分:0)

您需要告诉EF可以通过Article:

多次引用配置文件
modelBuilder.Entity<Article>()
    .HasOptional(a=>a.ApprovedBy)
    .WithMany()
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Article>()
    .HasOptional(a=>a.CreatedBy)
    .WithMany()
    .WillCascadeOnDelete(false);

如果属性是必需的,则HasOptional也可以是HasRequired(在DB中不为null)。 如果您想要(如您在样本中所做的那样)添加WithMany,则可以将配置文件与文章的多个属性(以及多个文章)相关联。

PS:我用内存写了这段代码,所以需要调整一些东西。

答案 2 :(得分:0)

你的专栏:

 .unmarshal(myInstanceGoesHere).

将附加pf,但它已被EF跟踪。你刚从数据库中得到它。 EF将重新插入pf,这会失败。只需删除该行就可以了。

Add/Attach and Entity States