2011-02-10 57 views
0

我試圖在實體框架中插入實體(使用代碼優先)時出現轉換異常。當我嘗試在實體框架中插入實體(使用代碼優先)時發生異常錯誤

演員的例外是像 「不可能投... Collection'1(實體)輸入(實體)」

從這個代碼:

public virtual T Insert(T entity) 
{ 
     return Context.Set<T>().Add(entity); 
} 

我想不通爲什麼。我很確定我做得很好。

郵政實體

public class Post 
    { 
     public long PostId { get; private set; } 
     public DateTime date { get; set; } 
     [Required] 
     public string Subject { get; set; } 
     public User User { get; set; } 
     public Category Category { get; set; } 
     [Required] 
     public string Body { get; set; } 

     public virtual ICollection<Tag> Tags { get; private set; } 

     public Post() 
     { 
      Category = new Category(); 
      if (Tags == null) 
       Tags = new Collection<Tag>(); 
     } 

     public void AttachTag(string name, User user) 
     { 
      if (Tags.Count(x => x.Name == name) == 0) 
       Tags.Add(new Tag { 
        Name = name, 
        User = user 
       }); 
      else 
       throw new Exception("Tag with specified name is already attached to this post."); 
     } 

     public Tag DeleteTag(string name) 
     { 
      Tag tag = Tags.Single(x => x.Name == name); 
      Tags.Remove(tag); 

      return tag; 
     } 

     public bool HasTags() 
     { 
      return (Tags.Count > 0); 
     } 
    } 

標籤實體

public class Tag 
{ 
    public long TagId { get; private set; } 
    public string Name { get; set; } 
    // Qui a ajouté le tag ? 
    public User User { get; set; } 
} 

映射

public class PostMap: EntityTypeConfiguration<Post> 
{ 
    public PostMap() 
    { 
     ToTable("Posts"); 
     HasKey(x => x.PostId); 
     Property(x => x.Subject) 
      .HasColumnType("varchar") 
      .HasMaxLength(256) 
      .IsRequired(); 
     Property(x => x.Body) 
      .HasColumnType("text") 
      .IsRequired(); 
     HasMany(x => x.Tags); 
     HasOptional(x => x.Tags); 
    } 
} 

class TagMap : EntityTypeConfiguration<Tag> 
{ 
    public TagMap() 
    { 
     ToTable("Tags"); 
     HasKey(x => x.TagId); 
     Property(x => x.Name) 
      .HasColumnType("varchar") 
      .HasMaxLength(256) 
      .IsRequired(); 
     HasRequired(x => x.User); 


} 
    } 

感謝很多。

回答

0

我找到了解決方案。

這裏正確的映射方案的帖子:

public PostMap() 
     { 
      ToTable("Posts"); 
      HasKey(x => x.PostId); 
      Property(x => x.Subject) 
       .HasColumnType("varchar") 
       .HasMaxLength(256) 
       .IsRequired(); 
      Property(x => x.Body) 
       .HasColumnType("text") 
       .IsRequired(); 
      HasRequired(x => x.User); 
      HasMany(x => x.Tags).WithOptional(); 
     } 

重要的是要指定的標籤集合是可選。在這種情況下,情況就是這樣。郵政可以附上零標籤。

HasMany(x => x.Tags).WithOptional();

0

請確保您已將單個元素傳遞給Insert方法,而不是包含單個元素的集合。

+0

我對此沒有任何控制權。 – Rushino 2011-02-10 12:58:23

相關問題