0

基於下面的代碼FluentAPI不能創建一個關係模型:映射的ICollection <string>流利API

public class Project 
{ 
    public Guid ID { get; private set; } 
    public string Name { get; set; } 
    public virtual ICollection<string> Images { get; set; } 
} 

public class ProjectConfiguration : EntityTypeConfiguration<Project> 
{ 
    public ProjectConfiguration() 
    { 
     HasKey(p => p.ID) 
      .Property(p => p.ID) 
       .IsRequired(); 

     Property(p => p.Name) 
      .HasMaxLength(60) 
      .IsRequired(); 

     HasRequired(p => p.Images).WithMany(); //???? Correct ?? 
     //HasMany(p => p.Images); //???? Correct ?? 
    } 
} 

錯誤

The navigation property 'Images' is not a declared property on type 'Project'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property. 

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.InvalidOperationException: The navigation property 'Images' is not a declared property on type 'Project'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property. 

Source Error: 


Line 58:   public IQueryable<Project> GetAll(int pageIndex, int pageSize, params Expression<Func<Project, object>>[] includeProperties) 
Line 59:   { 
Line 60:    return includeProperties.Aggregate<Expression<Func<Project, object>>, 
Line 61:     IQueryable<Project>>(Context.Projects, (current, includeProperty) => current.Include(includeProperty)).OrderBy(p => p.Name).Skip(pageIndex).Take(pageSize); 
Line 62:   } 

以下代碼ProjectRepository.cs

public IQueryable<Project> GetAll(params Expression<Func<Project, object>>[] includeProperties) 
{ 
    return includeProperties.Aggregate<Expression<Func<Project, object>>, 
     IQueryable<Project>>(Context.Projects, (current, includeProperty) => current.Include(includeProperty)); 
} 

public IQueryable<Project> GetAll(int pageIndex, int pageSize, params Expression<Func<Project, object>>[] includeProperties) 
{ 
    return includeProperties.Aggregate<Expression<Func<Project, object>>, 
     IQueryable<Project>>(Context.Projects, (current, includeProperty) => current.Include(includeProperty)).OrderBy(p => p.Name).Skip(pageIndex).Take(pageSize); 
} 

回答

2

收集的映射不支持原始類型的離子,它們不是有效的導航屬性。你必須定義一個實體類和Images集合中使用它,而不是string

public class Image 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public class Project 
{ 
    // ... 
    public virtual ICollection<Image> Images { get; set; } 
} 

新的實體Image將映射到其自身的新表。然後,您可以在Fluent API中定義映射:

public ProjectConfiguration() 
{ 
    // ... 
    HasMany(p => p.Images).WithRequired(); 
    // for a one-to-many relationship 
    // it will also setup cascading delete 
}