数据实体插入:已添加具有相同键的项

时间:2011-11-27 17:10:24

标签: c# asp.net entity-framework

我知道这个问题已被多次询问,经过帖子后,我认为它与实体名称有关,但我对数据实体模型完全不熟悉,同时尝试简单插入博客条目有了博客细节,我遇到了这个问题。

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: An item with the same key has already been added.

Source Error:

Line 365:    public void AddToblogs(blog blog)
Line 366:    {
Line 367:        base.AddObject("myblogs", blog);
Line 368:    }
Line 369:


Source File: C:\Inetpub\int422_113b16\webcontent\App_Code\blogModel.cs    Line: 367

Stack Trace:

[ArgumentException: An item with the same key has already been added.]
   System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
   System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +9382923
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadRelationshipTypes() +661
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() +17
   System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() +25
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.Load() +4
   System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) +160
   System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) +166
   System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) +316
   System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection edmItemCollection) +84
   System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) +151
   System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity) +211
   blogEntities.AddToblogs(blog blog) in C:\Inetpub\int422_113b16\webcontent\App_Code\blogModel.cs:367
   BlogManager.BlogAdd(String title, String content, String userName) in C:\Inetpub\int422_113b16\webcontent\App_Code\BlogManager.cs:27
   Project_Admin_create_post.post_Click(Object sender, EventArgs e) in C:\Inetpub\int422_113b16\webcontent\Project\Admin\create-post.aspx.cs:25
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

BlogManager.cs

public class BlogManager
{
    private blogEntities _dbEnt = new blogEntities();

    public BlogManager()
    {
    }

    public void BlogAdd(int numId, string title, string content,string userName) 
    {

        blog newPost = new blog();
        newPost.blog_id = 1;
        newPost.blog_title = title;
        newPost.blog_content = content;
        newPost.date_created = null;
        newPost.user_name = userName;

        _dbEnt.AddTotheblog(newPost);
        _dbEnt.SaveChanges();
    }

    public class NameNotUniqueException : Exception
    {
        public NameNotUniqueException(string msg = "INT422 ERROR: matching data already exists")
            : base(msg)
        { }
    }
}

创建-post.cs

public partial class Project_Admin_create_post : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            blogStatus.Text = "Your post is published";
            title.Enabled = false;
            content.Enabled = false;
        }
    }

    protected void post_Click(object sender, EventArgs e)
    {
        string _userName = User.Identity.Name;

        BlogManager blogMgr = new BlogManager();
        blogMgr.BlogAdd(title.Text, content.Text, _userName);
    }
}

2 个答案:

答案 0 :(得分:1)

我认为错误信息在这里告诉你真相。您之前,无论是在博客文章中的子对象中,还是博客帖子本身 - 使用相同的实体密钥添加了此类型的另一个实体。

您的某个表中是否有可能忘记为PK设置身份密钥?如果是这样,您可能有一个键为0的行,后续插入与它冲突。

答案 1 :(得分:0)

if(blog.EntityState==EntityState.Detached)
    base.AddObject("myblogs", blog);