Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I properly get the entity framework to use my composite primary key?
    primarykey
    data
    text
    <p>I have a table defined as such:</p> <pre><code>CREATE TABLE [dbo].[Sitemap]( [EntityId] [int] NOT NULL, [PageUrl] [nvarchar](400) NOT NULL, [Frequency] [nvarchar](400) NOT NULL, [PageType] [nvarchar](400) NOT NULL, [UpdatedOn] [datetime] NOT NULL, CONSTRAINT [PK_Sitemap] PRIMARY KEY CLUSTERED ( [EntityId] ASC, [PageType] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>I went to my edmx file and did an update from database. It imported everything but didn't mark both fields as a primary key. I tried added the second field as a primary key, but it still won't treat them as composites.</p> <p>The issue I am having is when I run an update at the table that has a similar entry such as </p> <p>EntityId = 1, PageType = 'Product',.... and EntityId = 1, PageType = 'Artist',...</p> <p>I am getting an error saying:</p> <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p> <p>How do I get my Model or code to properly use the composite as the primary key? Or do I have to make some kind of composite field to do this?</p> <p><strong>UPDATE</strong></p> <p>My Code is a fork from NopCommerce 1.90</p> <p>As such I have added an interface and service and registered that with the IoC resolver.</p> <p>I have the following class that for this table:</p> <pre><code>//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement; using NopSolutions.NopCommerce.BusinessLogic.Infrastructure; using NopSolutions.NopCommerce.BusinessLogic.Payment; using NopSolutions.NopCommerce.BusinessLogic.Promo.Affiliates; using NopSolutions.NopCommerce.BusinessLogic.Promo.Discounts; using NopSolutions.NopCommerce.BusinessLogic.Shipping; using NopSolutions.NopCommerce.BusinessLogic.Tax; namespace NopSolutions.NopCommerce.BusinessLogic.SEO.Sitemaps { /// &lt;summary&gt; /// Represents a Sitemap /// &lt;/summary&gt; [Serializable] public partial class Sitemap : BaseEntity { #region Utilities #endregion #region Properties /// &lt;summary&gt; /// Gets or Sets EntityId (Product ID, Show ID, etc.) /// &lt;/summary&gt; public int EntityId { get; set; } /// &lt;summary&gt; /// Gets or sets the Page Url /// &lt;/summary&gt; public string PageUrl { get; set; } /// &lt;summary&gt; /// Gets of set the Page Frequency (Should be one of the following - Always, Hourly, Daily, Weekly, Monthly, Yearly, Never) /// &lt;/summary&gt; public string Frequency { get; set; } /// &lt;summary&gt; /// Gets or sets the page type. For example: Product, or Show /// &lt;/summary&gt; public string PageType { get; set; } /// &lt;summary&gt; /// Gets or sets the date and time of sitemap entry update /// &lt;/summary&gt; public DateTime UpdatedOn { get; set; } #endregion } } </code></pre> <p>Then I have the interface and service:</p> <p>Interface:</p> <pre><code> //------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement; using NopSolutions.NopCommerce.BusinessLogic.Payment; using NopSolutions.NopCommerce.BusinessLogic.Shipping; using NopSolutions.NopCommerce.Common; namespace NopSolutions.NopCommerce.BusinessLogic.SEO.Sitemaps { /// &lt;summary&gt; /// Sitemap service /// &lt;/summary&gt; public partial interface ISiteMapService { /// &lt;summary&gt; /// Gets a Sitemap entry based on url. /// &lt;/summary&gt; /// &lt;param name="url"&gt;Fully Qualified URL (e.g. http://www.onlinesheetmusic.com/default.aspx)&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; Sitemap GetSitemap(string url); /// &lt;summary&gt; /// Gets the most recent entry to the sitemap table /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; Sitemap GetLastAddedSitemap(string pageType); /// &lt;summary&gt; /// Gets a list of Sitemap entries that are in the init state of the given Page Type /// &lt;/summary&gt; /// &lt;param name="pageType"&gt;Page Type&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; List&lt;Sitemap&gt; GetInitEntries(string pageType); /// &lt;summary&gt; /// Bool to determine if a given pageType has any entries in the init state. /// &lt;/summary&gt; /// &lt;param name="pageType"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; bool IsInit(string pageType); void InitSitemap(string pageType, int startProdId = 0); /// &lt;summary&gt; /// Inserts a sitemap entry /// &lt;/summary&gt; /// &lt;param name="order"&gt;Order&lt;/param&gt; void InsertSitemap(Sitemap sm); /// &lt;summary&gt; /// Updates the order /// &lt;/summary&gt; /// &lt;param name="order"&gt;The order&lt;/param&gt; void UpdateSitemap(Sitemap sm); } } </code></pre> <p>Service:</p> <pre><code>//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NopSolutions.NopCommerce.BusinessLogic.Audit; using NopSolutions.NopCommerce.BusinessLogic.Caching; using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings; using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement; using NopSolutions.NopCommerce.BusinessLogic.Data; using NopSolutions.NopCommerce.BusinessLogic.Directory; using NopSolutions.NopCommerce.BusinessLogic.Infrastructure; using NopSolutions.NopCommerce.BusinessLogic.Localization; using NopSolutions.NopCommerce.BusinessLogic.Messages; using NopSolutions.NopCommerce.BusinessLogic.Messages.SMS; using NopSolutions.NopCommerce.BusinessLogic.Payment; using NopSolutions.NopCommerce.BusinessLogic.Products; using NopSolutions.NopCommerce.BusinessLogic.Products.Attributes; using NopSolutions.NopCommerce.BusinessLogic.Profile; using NopSolutions.NopCommerce.BusinessLogic.Promo.Discounts; using NopSolutions.NopCommerce.BusinessLogic.QuickBooks; using NopSolutions.NopCommerce.BusinessLogic.Security; using NopSolutions.NopCommerce.BusinessLogic.Shipping; using NopSolutions.NopCommerce.BusinessLogic.Tax; using NopSolutions.NopCommerce.Common; using NopSolutions.NopCommerce.Common.Extensions; using NopSolutions.NopCommerce.Common.Utils; using NopSolutions.NopCommerce.Common.Utils.Html; namespace NopSolutions.NopCommerce.BusinessLogic.SEO.Sitemaps { /// &lt;summary&gt; /// Sitemap service /// &lt;/summary&gt; public partial class SiteMapService : ISiteMapService { #region Fields /// &lt;summary&gt; /// Object context /// &lt;/summary&gt; private readonly NopObjectContext _context; /// &lt;summary&gt; /// Cache service /// &lt;/summary&gt; private readonly ICacheManager _cacheManager; #endregion Fields #region Ctor /// &lt;summary&gt; /// Ctor /// &lt;/summary&gt; /// &lt;param name="context"&gt;Object context&lt;/param&gt; public SiteMapService(NopObjectContext context) { this._context = context; this._cacheManager = new NopRequestCache(); } #endregion Ctor #region Utilities #endregion Utilities #region Methods /// &lt;summary&gt; /// Gets a sitemap entry /// &lt;/summary&gt; /// &lt;param name="url"&gt;The url of the sitempa item&lt;/param&gt; /// &lt;returns&gt;Order&lt;/returns&gt; public Sitemap GetSitemap(string url) { if (!url.IsNotNullOrEmpty()) return null; var query = from sm in _context.Sitemaps where sm.PageUrl.Contains(url) select sm; var sitemap = query.SingleOrDefault(); return sitemap; } public Sitemap GetLastAddedSitemap(string pageType) { var query = (from sm in _context.Sitemaps where sm.PageType.Equals(pageType) orderby sm.UpdatedOn descending select sm).Take(1); var sitemap = query.SingleOrDefault(); return sitemap; } public List&lt;Sitemap&gt; GetInitEntries(string pageType) { var query = (from sm in _context.Sitemaps where sm.PageType.Equals(pageType) &amp;&amp; sm.Frequency == "Init" select sm).Take(500); return query.ToList(); } /// &lt;summary&gt; /// Bool to check if a given type has any entries in the init state. /// &lt;/summary&gt; /// &lt;param name="pageType"&gt;Page Type&lt;/param&gt; /// &lt;returns&gt;True or False&lt;/returns&gt; public bool IsInit(string pageType) { var query = (from sm in _context.Sitemaps where sm.PageType.Equals(pageType) &amp;&amp; sm.PageUrl.Equals("Init") select sm).Take(1); if (query == null) return true; else return false; } public void InitSitemap(string pageType, int startProdId = 0) { _context.Sp_SitemapInit(pageType, startProdId); } /// &lt;summary&gt; /// Inserts a sitemap entry /// &lt;/summary&gt; /// &lt;param name="sm"&gt;Sitemap Entry to Insert&lt;/param&gt; public void InsertSitemap(Sitemap sm) { if (sm == null) throw new ArgumentNullException("sitemap"); sm.PageUrl = CommonHelper.EnsureNotNull(sm.PageUrl); sm.PageType = CommonHelper.EnsureNotNull(sm.PageType); sm.Frequency = CommonHelper.EnsureNotNull(sm.Frequency); _context.Sitemaps.AddObject(sm); _context.SaveChanges(); } /// &lt;summary&gt; /// Updates a sitemap entry /// &lt;/summary&gt; /// &lt;param name="sm"&gt;Sitemap Entry to update&lt;/param&gt; public void UpdateSitemap(Sitemap sm) { if (sm == null) throw new ArgumentNullException("sitemap"); sm.PageUrl = CommonHelper.EnsureNotNull(sm.PageUrl); sm.PageType = CommonHelper.EnsureNotNull(sm.PageType); sm.Frequency = CommonHelper.EnsureNotNull(sm.Frequency); if(_context.Sitemaps.Any(s =&gt; (s.PageUrl == sm.PageUrl || s.EntityId == sm.EntityId))) { if (!_context.IsAttached(sm)) _context.Sitemaps.Attach(sm); } else { _context.Sitemaps.AddObject(sm); } _context.SaveChanges(); } #endregion Methods #region Properties /// &lt;summary&gt; /// Gets a value indicating whether cache is enabled /// &lt;/summary&gt; public bool CacheEnabled { get { return IoC.Resolve&lt;ISettingManager&gt;().GetSettingValueBoolean("Cache.OrderManager.CacheEnabled"); } } #endregion Properties } } </code></pre> <p>When I call</p> <pre><code>var sitemapservice = IoC.Resolve&lt;ISiteMapService&gt;(); sitemapservice.InitSitemap("Artist"); var smEntries = sitemapservice.GetInitEntries("Artist"); foreach (Sitemap sm in smEntries) { using (MvcMiniProfiler.MiniProfiler.StepStatic("Processing Entry: " + sm.EntityId + "," + sm.PageType)) { sm.Frequency = "Monthly"; sm.PageUrl = SEOHelper.GetUrl(this.ArtistService.GetArtistById(sm.EntityId), this.SettingManager.StoreUrl); using (MvcMiniProfiler.MiniProfiler.StepStatic("Updating database")) { sitemapservice.UpdateSitemap(sm); } curCount++; } } </code></pre> <p>It is supposed to get all the entries that are in the init stage and set them up with the correct url, but for whatever reason I keep getting errors saying An object with the same key already exists in the ObjectStateManager. Though the strange thing is the DB seems to be updating properly it just keeps giving me this error.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload