使用EF添加对象时找到不明确的匹配

时间:2014-02-18 14:56:45

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

我发现这个模棱两可的比赛突然发现了错误。我无法弄清楚造成它的原因。我正在使用MVC和Entity Famework。任何帮助将不胜感激。

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.<BeginInvokeSynchronousActionMethod>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.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c() +50   System.Web.Mvc.Async.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e() +225   System.Web.Mvc.Async.<>c__DisplayClass30.<BeginInvokeActionMethodWithFilters>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.<>c__DisplayClass28.<BeginInvokeAction>b__19() +26   System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>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.<BeginExecuteCore>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.<BeginExecute>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.<BeginProcessRequest>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& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446

这是发生错误的方法。我用底部的注释标记了错误的位置。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MultiFileUpload(IEnumerable<HttpPostedFileBase> uplMultipleFiles, string galleryItemID)
    {
        if (uplMultipleFiles != null && 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() > 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");
        }

    }

这是它试图添加项目的GalleryItemFile类。

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

}

任何帮助都将不胜感激。

这是Chris所要求的GalleryItem类。

public class GalleryItem
{
    [Key]
    public int galleryItemID { get; set; }

    public string imageName { get; set; }

    [MaxLength(250)]
    public string description { get; set; }
    public List<string> 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<GalleryItemFile> GalleryItemFiles { get; set; }

    public virtual List<GalleryTag> Tags { get; set; }

    public virtual GalleryCollection collection { get; set; }
    public virtual GalleryCategory category { get; set; }


    //public GalleryItem()
    //{
    //    this.GalleryItemFiles = new List<GalleryItemFile>();
    //}
}

2 个答案:

答案 0 :(得分:3)

作为评论可能会更好,但我没有它的声誉......

您获得的异常与反射有关。在我看来,当EF试图在由EF创建的GalleryItem代理和您的GalleryItem类型之间进行映射时,会发生这种异常。 (EF创建一个代理来启用延迟加载等)。您的问题可能与该类有关,如果您为其发布了源代码,它会有所帮助。以下是反射GetProperty方法的一般描述(请参阅Exceptions部分中的AmbiguousMatchException)。

http://msdn.microsoft.com/en-us/library/kz0a8sxy(v=vs.110).aspx

答案 1 :(得分:0)

我也遇到过这个问题。这个链接AmbiguousMatchException说:

  

绑定到成员时引发的异常会导致更多异常   比一个符合绑定标准的成员。这堂课不可能   继承的。

我的代码很简单。我在基类object中为Id属性使用了AEntity类型,但在int实体中使用了Person。使用Id的相同类型解决了我的问题。

  [Table("Person")]
    public sealed partial class Person: AEntity
    {
        [Key]
        public int Id { get; set; }
    }


    [Serializable]
    public class AEntity : IEntity
    {
        public object Id { get; set; }
    }

    public interface IEntity
    {
        object Id { get; set; }
    }