2012-07-16 18 views
7

He estado utilizando Entity Framework en una solución .NET 4.0 durante unas semanas. Es EF 4.3.1. Primero creé el esquema de la base de datos y generé mis Objetos de Entidad usando la plantilla "EF4.x DbContext Generator".No se puede establecer el campo/propiedad en el tipo de entidad con Entity Framework 4.3.1

Tenía tres tablas en el esquema y todo funcionaba bien con métodos CRUD simples.

Ahora he agregado una cuarta tabla, "Temas", que tiene una referencia de clave externa a una tabla existente "SourceUri", tal que una SourceUri puede tener 0-muchas materias, y un Subject tiene exactamente una SourceUri.

He actualizado mi modelo de edmx y parece correcto. Sin embargo, no importa lo que intente, parece que no puede hacer lo siguiente:

  • añadir un nuevo registro SourceUri
  • añadir uno o más sujetos para la nueva SourceUri

Este es el código que Actualmente estoy intentando. Puedes ver que estoy guardando el contexto regularmente, pero originalmente solo estaba guardando los cambios una vez al final del método.

/// <summary> 
    /// Adds a new Source URI to the system 
    /// </summary> 
    /// <param name="sourceUri">The source URI to add</param> 
    /// <param name="subjectNames">List of subjects for this source URI, in order</param> 
    /// <returns>The added source URI</returns> 
    public SourceUri AddSourceUri(SourceUri sourceUri, IList<string> subjectNames) 
    { 
     try 
     { 
      _logger.Debug("Adding new source URI '{0}', with '{1}' subjects.", sourceUri.Uri, 
       subjectNames != null ? subjectNames.Count : 0); 
      LogSourceUriDetails(sourceUri, "Adding"); 

      using (var dbContext = GetDbContext()) 
      { 
       dbContext.SourceUris.Add(sourceUri); 
       dbContext.SaveChanges(); // this save succeeds 

       // add the subjects if there are any 
       if (subjectNames != null) 
       { 
        for (int i = 0; i < subjectNames.Count; i++) 
        { 
         Subject newSubject = new Subject() 
               { 
                DisplayOrder = i, 
                SourceUriId = sourceUri.SourceUriId, 
                SubjectText = subjectNames.ElementAt(i).Trim() 
               }; 
         _logger.Debug("Adding new subject '{0}' to source URI '{1}'.", newSubject.SubjectText, 
             sourceUri.Uri); 
         dbContext.Subjects.Add(newSubject); // this line fails 
         dbContext.SaveChanges(); 
        } 
       } 

       _logger.Debug("Successfully added new source URI '{0}' with '{1}' subjects. Source URI ID is '{2}'.", 
        sourceUri.Uri, subjectNames != null ? subjectNames.Count : 0, sourceUri.SourceUriId); 
       return sourceUri; 
      } 
     } 
     catch (Exception exception) 
     { 
      _logger.ErrorException(string.Format("An error occurred adding new source URI '{0}' with '{1}' subjects.", 
       sourceUri.Uri, subjectNames != null ? subjectNames.Count : 0), exception); 
      throw; 
     } 
    } 

El código agrega la nueva SourceUri y guarda los cambios. Sin embargo, no logra agregar el nuevo sujeto al contexto de datos. No llega a intentar salvar ese cambio.

La excepción es:

Unable to set field/property Subjects on entity type CommentService.DomainObjects.SourceUri. See InnerException for details. 
System.Data.Objects.Internal.PocoPropertyAccessorStrategy.CollectionRemove(RelatedEnd relatedEnd, Object value) 
System.Data.Objects.Internal.EntityWrapper`1.CollectionRemove(RelatedEnd relatedEnd, Object value) 
System.Data.Objects.DataClasses.EntityCollection`1.RemoveFromObjectCache(IEntityWrapper wrappedEntity) 
System.Data.Objects.DataClasses.RelatedEnd.Remove(IEntityWrapper wrappedEntity, Boolean doFixup, Boolean deleteEntity, Boolean deleteOwner, Boolean applyReferentialConstraints, Boolean preserveForeignKey) 
System.Data.Objects.DataClasses.RelatedEnd.FixupOtherEndOfRelationshipForRemove(IEntityWrapper wrappedEntity, Boolean preserveForeignKey) 
System.Data.Objects.DataClasses.RelatedEnd.Remove(IEntityWrapper wrappedEntity, Boolean doFixup, Boolean deleteEntity, Boolean deleteOwner, Boolean applyReferentialConstraints, Boolean preserveForeignKey) 
System.Data.Objects.DataClasses.EntityReference`1.Exclude() 
System.Data.Objects.DataClasses.RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(IEntityWrapper wrappedEntity) 
System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity) 
System.Data.Entity.Internal.Linq.InternalSet`1.&lt;&gt;c__DisplayClass5.&lt;Add&gt;b__4() 
System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) 
System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity) 
System.Data.Entity.DbSet`1.Add(TEntity entity) 
CommentService.Business.Managers.SourceUriManager.AddSourceUri(SourceUri sourceUri, IList`1 subjectNames) in C:\Projects\SVN Misc Projects\CommentService\trunk\CommentService.Business\Managers\SourceUriManager.cs:line 152 
CommentService.Web.Comment.AddSourceUri(SourceUri sourceUri, IList`1 subjectNames) in C:\Projects\SVN Misc Projects\CommentService\trunk\CommentService.Web\Comment.svc.cs:line 173 
SyncInvokeAddSourceUri(Object , Object[] , Object[]) 
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) 
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc) 
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) 

he ido dando vueltas y vueltas en esto, y he visto varias excepciones ligeramente diferentes. Todos parecen apuntar al hecho de que la propiedad de navegación Subject del objeto SourceUri es de alguna manera de solo lectura o de longitud fija (¿matriz?).

Las clases de entidad generados mirada como sigue:

//------------------------------------------------------------------------------ 
// <auto-generated> 
// This code was generated from a template. 
// 
// Manual changes to this file may cause unexpected behavior in your application. 
// Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace CommentService.DomainObjects 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class SourceUri 
    { 
     public SourceUri() 
     { 
      this.Comments = new HashSet<Comment>(); 
      this.Subjects = new HashSet<Subject>(); 
     } 

     public long SourceUriId { get; set; } 
     public string Uri { get; set; } 
     public string Description { get; set; } 
     public System.DateTime DateCreated { get; set; } 
     public string AdminUser { get; set; } 

     public virtual ICollection<Comment> Comments { get; set; } 
     public virtual ICollection<Subject> Subjects { get; set; } 
    } 
} 


//------------------------------------------------------------------------------ 
// <auto-generated> 
// This code was generated from a template. 
// 
// Manual changes to this file may cause unexpected behavior in your application. 
// Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace CommentService.DomainObjects 
{ 
    using System; 
    using System.Collections.Generic; 

    public partial class Subject 
    { 
     public Subject() 
     { 
      this.Comments = new HashSet<Comment>(); 
     } 

     public long SubjectId { get; set; } 
     public long SourceUriId { get; set; } 
     public string SubjectText { get; set; } 
     public int DisplayOrder { get; set; } 

     public virtual ICollection<Comment> Comments { get; set; } 
     public virtual SourceUri SourceUri { get; set; } 
    } 
} 

¿Por qué no funciona?

Lista rápida de las cosas que he comprobado/intentaron:

  • El esquema de base de datos es correcta - Puedo insertar registros como se esperaba con SQL y primarias claves, claves externas e identidades parecen estar comportándose correctamente
  • El modelo parece reflejar correctamente el esquema de la base de datos, incluidas las identidades PK (EntityKey = true, StoreGeneratedPattern = Identity)
  • Logré que EF mantenga datos en mi esquema, pero una vez insertados los datos, se lanza una excepción afirmando que el contexto podría estar fuera de sincronización, una vez más relacionado con no poder para actualizar la propiedad de navegación de temas del objeto SourceUri
  • He intentado agregar los temas a la colección dbContext.Subjects, y también a la colección SourceUri.Subjects. También intenté establecer la propiedad SourceUri del Sujeto en lugar de la propiedad SourceUriId del Sujeto.
+0

"* Ver InnerException para más detalles." * Dice que el primer línea en el rastro de la pila. ¿Puedes hacer eso y agregar el mensaje de excepción interno a tu pregunta? – Slauma

+0

La excepción interna es nula. –

Respuesta

14

He llegado al fondo de este problema. El comportamiento problemático fue causado por la entidad SourceUri que se pasó al método a través de un servicio web WCF.Significaba que las propiedades de ICollection del objeto se estaban deserializando como una matriz, que es de longitud fija y no se puede agregar a.

que han resuelto este problema mediante la alteración de la plantilla que genera mis entidades para que produzca clases donde las colecciones son listas de forma explícita, de la siguiente manera:

//------------------------------------------------------------------------------ 
// <auto-generated> 
// This code was generated from a template. 
// 
// Manual changes to this file may cause unexpected behavior in your application. 
// Manual changes to this file will be overwritten if the code is regenerated. 
// </auto-generated> 
//------------------------------------------------------------------------------ 

namespace CommentService.DomainObjects 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Linq; // added this 

    public partial class SourceUri 
    { 
     public SourceUri() 
     { 
      this.Comments = new HashSet<Comment>().ToList(); // added this 
      this.Subjects = new HashSet<Subject>().ToList(); // added this 
     } 

     public long SourceUriId { get; set; } 
     public string Uri { get; set; } 
     public string Description { get; set; } 
     public System.DateTime DateCreated { get; set; } 
     public string AdminUser { get; set; } 

     public virtual List<Comment> Comments { get; set; } // altered these to List 
     public virtual List<Subject> Subjects { get; set; } // altered these to List 
    } 
} 
Cuestiones relacionadas