2012-07-16 81 views
7

我一直在.NET 4.0解决方案中使用实体框架几周。这是EF 4.3.1。我首先创建了数据库模式,并使用“EF4.x DbContext生成器”模板生成了我的实体对象。无法使用实体框架设置实体类型的字段/属性4.3.1

我在模式中有三个表格,并且它使用简单的CRUD方法都可以正常工作。

我现在添加了第四个表“主题”,它具有对现有表“SourceUri”的外键引用,使得SourceUri可以具有0多个主题,并且主题只有一个SourceUri。

我更新了我的edmx模型,它看起来正确。但是,不管我怎么努力,我似乎​​无法做到以下几点:

  • 添加新SourceUri记录
  • 添加一个或多个科目为新SourceUri

这是我的代码我正在尝试。您可以看到我经常保存上下文,但最初我只是在方法结束时保存一次更改。

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

该代码添加新的SourceUri并保存更改。但是,它无法将新主题添加到数据上下文中。它不会尽力保存这种变化。

唯一的例外是:

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) 

我已经团团此,也见过几个稍有不同的异常。它们似乎都指向SourceUri对象的Subjects导航属性以某种方式是只读或固定长度(数组?)的事实。

生成的实体类如下所示:

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

为什么不这项工作?

快速的事情,我已经检查列表/试过:

  • 数据库架构看起来是正确的 - 我可以插入记录与SQL和主键,外键和身份预期似乎是正确的行为
  • 该模型似乎正确地反映了数据库模式,包括PK身份(EntityKey = true,StoreGeneratedPattern = Identity)
  • 我设法让EF将数据保存到我的模式中,但是插入数据后引发异常指出上下文可能不同步 - 再次涉及不能更新SourceUri对象的主题导航属性
  • 我已经尝试将主题添加到dbContext.Subjects集合,并且还添加到SourceUri.Subjects集合。我也尝试设置主题的SourceUri属性而不是主题的SourceUriId属性。
+0

“*请参阅的InnerException了解详细信息。” *说第一在堆栈跟踪线。你能做到这一点,并添加内部异常信息到你的问题? – Slauma 2012-07-16 12:12:17

+0

内部异常为空。 – 2012-07-16 13:03:30

回答

14

我已经到了这个问题的底部。问题行为是由SourceUri实体通过WCF Web服务传递给方法引起的。这意味着该对象的ICollection属性被反序列化为一个Array,该Array是固定长度的,并且不能被添加到。

我已经改变,生成我的实体,使其产生,其中集合是明确列出类模板解决了这个问题,具体如下:

//------------------------------------------------------------------------------ 
// <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 
    } 
} 
相关问题