Я получаю этот неоднозначный результат, обнаружив ошибку внезапно. Я не могу понять, что вызывает его. Я использую MVC и Entity Famework. Любая помощь была бы оценена.Неоднозначное совпадение, найденное при добавлении объекта с помощью EF
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; }
}
Любая помощь будет принята с благодарностью.
Это класс 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>();
//}
}
Это может произойти, если у вас есть свойства в POCO, имеющие одно и то же имя, дифференцированные только в зависимости от случая. Не видите ничего подобного в 'GalleryFileItem', но можете ли вы дважды проверить свой класс' GalleryItem'? –
Это может неудивительно также возникнуть, если у вас есть несколько свойств в POCO с таким же именем (в том же случае), например. через использование наследования и ключевое слово 'new'. – Josh