title: Ambiguous Match Found when adding object with EF
body: <p>I am getting this ambiguous match found error all of the sudden. I can't figure out what is causing it. I am using MVC and Entity Famework. Any help would be appreciated it. </p>
  
  <pre><code>Ambiguous match found.
  
  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.Reflection.AmbiguousMatchException: Ambiguous match found.
  
  Source Error: 
  
  Line 355:                        //Save Object to DBLine 356:                        if (matchFound) { db.Entry(galleryFile).State = EntityState.Modified; }Line 357:                        else { db.GalleryItemFiles.Add(galleryFile); }Line 358:                        db.SaveChanges();Line 359:
  
  Source File: c:\Users\holcombelr\SkyDrive\Public\Projects\UHV\Marketing\Marketing\Marketing\Areas\Intranet\Controllers\GalleryItemFileController.cs    Line: 357 
  
  Stack Trace: 
  
  [AmbiguousMatchException: Ambiguous match found.]   System.RuntimeType.GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) +10615074   System.Type.GetProperty(String name, BindingFlags bindingAttr) +30   System.Linq.Expressions.Expression.PropertyOrField(Expression expression, String propertyOrFieldName) +47   System.Data.Entity.Core.Objects.Internal.EntityProxyFactory.CreateBaseGetter(Type declaringType, PropertyInfo propertyInfo) +79   System.Data.Entity.Core.Objects.Internal.PocoPropertyAccessorStrategy.GetNavigationPropertyValue(RelatedEnd relatedEnd) +148   System.Data.Entity.Core.Objects.Internal.EntityWrapper`1.GetNavigationPropertyValue(RelatedEnd relatedEnd) +19   System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInRelationshipsOfSingleEntity() +200   System.Data.Entity.Core.Objects.ObjectStateManager.DetectChangesInNavigationProperties(IList`1 entries) +77   System.Data.Entity.Core.Objects.ObjectStateManager.DetectChanges() +81   System.Data.Entity.Core.Objects.ObjectContext.DetectChanges() +19   System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) +34   System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +74   System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity) +108   System.Data.Entity.DbSet`1.Add(TEntity entity) +72   Marketing.Areas.Intranet.Controllers.GalleryItemFileController.MultiFileUpload(IEnumerable`1 uplMultipleFiles, String galleryItemID) in c:\Users\holcombelr\SkyDrive\Public\Projects\UHV\Marketing\Marketing\Marketing\Areas\Intranet\Controllers\GalleryItemFileController.cs:357   lambda_method(Closure , ControllerBase , Object[] ) +127   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27   System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;BeginInvokeSynchronousActionMethod&gt;b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32   System.Web.Mvc.Async.AsyncInvocationWithFilters.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3c() +50   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass45.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__3e() +225   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass30.&lt;BeginInvokeActionMethodWithFilters&gt;b__2f(IAsyncResult asyncResult) +10   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass28.&lt;BeginInvokeAction&gt;b__19() +26   System.Web.Mvc.Async.&lt;&gt;c__DisplayClass1e.&lt;BeginInvokeAction&gt;b__1b(IAsyncResult asyncResult) +100   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27   System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39   System.Web.Mvc.Controller.&lt;BeginExecute&gt;b__15(IAsyncResult asyncResult, Controller controller) +12   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10   System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +21   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514928   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
  
  Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446
  </code></pre>
  
  <p>Here is the Method that the error occurs in. I marked the location of the error with the comment toward the bottom.</p>
  
  <pre><code>[HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult MultiFileUpload(IEnumerable&lt;HttpPostedFileBase&gt; uplMultipleFiles, string galleryItemID)
      {
          if (uplMultipleFiles != null &amp;&amp; Common.IsNumeric(galleryItemID))
          {
              //Initialize Objects
              GalleryItem galleryItem;
              GalleryItemFile galleryFile = new GalleryItemFile();
              galleryItem = db.GalleryItems.Find(Convert.ToInt32(galleryItemID));
  
              //Check that we were able to get an GalleryItem
              if (galleryItem != null)
              {
                  galleryFile.galleryItem = galleryItem;
  
                  //Loop through the uploaded files
                  foreach (var thisFile in uplMultipleFiles)
                  {
                      //Check if we already have a file with the current extension
                      string extension = Path.GetExtension(thisFile.FileName);
                      var matchedGalleryFiles = (from g in galleryItem.GalleryItemFiles
                                                         where g.extension == extension
                                                         select g);
  
                      GalleryItemFile matchedGalleryFile = null;
                      if (matchedGalleryFiles.Any())
                      { 
                          matchedGalleryFile = matchedGalleryFiles.First();
                      }
  
                      bool matchFound = false;
  
                      if (matchedGalleryFile != null)
                      {
                          galleryFile = matchedGalleryFile;
                          matchFound = true;
                      }
  
                      //Create .jpg Thumbnail and Preview
                      if (extension.ToLower() == ".jpg")
                      {
  
                          string thumbnailFilename = galleryFile.galleryItem.imageName.Replace(" ", "-").Replace("'", "") + "-TH.jpg";
                          string previewFilename = galleryFile.galleryItem.imageName.Replace(" ", "-").Replace("'", "") + "-PR.jpg";
  
                          //setup filepath and save
                          //thisFile.SaveAs(Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), thumbnailFilename));
                          if (System.IO.File.Exists(Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), thumbnailFilename)))
                          { System.IO.File.Delete(Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), thumbnailFilename)); }
  
                          if (System.IO.File.Exists(Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), previewFilename)))
                          { System.IO.File.Delete(Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), previewFilename)); }
  
                          FileTools.SaveFile(FileTools.ResizeImage(FileTools.StreamToImage(thisFile.InputStream), 150, 150), Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), thumbnailFilename));
                          FileTools.SaveFile(FileTools.ResizeImage(FileTools.StreamToImage(thisFile.InputStream), 600, 600), Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), previewFilename));
                      }
  
  
                      //Get FileType
                      var fileTypes = from f in db.GalleryFileTypes
                                      where f.extension == extension
                                      select f;
  
                      if (fileTypes.Count() &gt; 0)
                      {
                          galleryFile.fileType = fileTypes.First();
                      }
                      else
                      {
                          fileTypes = from f in db.GalleryFileTypes
                                      where f.fileType.ToLower() == "other"
                                      select f;
  
                          galleryFile.fileType = fileTypes.First();
                      }
  
  
                      //setup filename
                      string filename = galleryFile.galleryItem.imageName + "-" + DateTime.Now.ToString("yyyyMMdd-HHmm-ss");
                      filename = filename.Replace(" ", "-").Replace("'", "") + Path.GetExtension(thisFile.FileName);
  
                      //setup filepath and save
                      string filepath = Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryFiles"), filename);
                      thisFile.SaveAs(filepath);
  
                      //delete old file
                      if (System.IO.File.Exists(Server.MapPath(galleryFile.filepath)))
                      { System.IO.File.Delete(Server.MapPath(galleryFile.filepath)); }
  
                      //Give filename and filepath to object
                      galleryFile.filename = filename;
                      galleryFile.filepath = Path.Combine("~/Areas/Gallery/Content/GalleryFiles", filename);
                      galleryFile.extension = extension;
  
                      //Save Object to DB
                      if (matchFound) { db.Entry(galleryFile).State = EntityState.Modified; }
                      else { db.GalleryItemFiles.Add(galleryFile); } **// ERROR OCCURS HERE**
                      db.SaveChanges();
  
                  }
  
                  return Content("");
              }
              else { return Content("Error"); }
          }
          else
          {
              return Content("Error");
          }
  
      }
  </code></pre>
  
  <p>This is the GalleryItemFile class that it is trying to add the item too.</p>
  
  <pre><code>public class GalleryItemFile
  {
      [Key]
      public int fileID { get; set; }
  
      public virtual GalleryItem galleryItem { get; set; }
  
      public virtual GalleryFileType fileType { get; set; }
  
      public string filename { get; set; }
  
      public string filepath { get; set; }
  
      public string extension { get; set; }
  
      public bool active { get; set; }
  
      public DateTime? createdOn { get; set; }
  
      [MaxLength(150)]
      public string createdBy { get; set; }
  
      public string createdByUserName { get; set; }
  
      public DateTime? lastUpdatedOn { get; set; }
  
      [MaxLength(150)]
      public string lastUpdatedBy { get; set; }
  
      public string lastUpdatedByUserName { get; set; }
  
      public int? width { get; set; }
      public int? height { get; set; }
  
  }
  </code></pre>
  
  <p>Any help would be appreciated.</p>
  
  <p>Here is the GalleryItem class as requested by Chris.</p>
  
  <pre><code>public class GalleryItem
  {
      [Key]
      public int galleryItemID { get; set; }
  
      public string imageName { get; set; }
  
      [MaxLength(250)]
      public string description { get; set; }
      public List&lt;string&gt; tags { get; set; }
  
      [MaxLength(250)]
      public string restrictions { get; set; }
      public DateTime? createdOn { get; set; }
      public string createdBy { get; set; }
      public string createdByUserName { get; set; }
      public DateTime? lastUpdatedOn { get; set; }
      public string lastUpdatedBy { get; set; }
      public string lastUpdatedByUserName { get; set; }
  
      public virtual List&lt;GalleryItemFile&gt; GalleryItemFiles { get; set; }
  
      public virtual List&lt;GalleryTag&gt; Tags { get; set; }
  
      public virtual GalleryCollection collection { get; set; }
      public virtual GalleryCategory category { get; set; }
  
  
      //public GalleryItem()
      //{
      //    this.GalleryItemFiles = new List&lt;GalleryItemFile&gt;();
      //}
  }
  </code></pre>