在Entity Framework中使用ModelConfiguration给出错误“不是有效的属性表达式”

时间:2014-09-25 23:34:42

标签: c# entity-framework

在我的C#项目中,当EF尝试创建我的数据库时出现错误 当我打电话

时发生错误
Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDatabase>());

错误消息是

The expression 'x => x.Dependancies' is not a valid property expression. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'.

我的域类如下

[Table("LoggedEntity")]
public class LoggedEntity
{
    public int Id { get; set; }
}

[Table("TemplateTaskDependancy")]
public class TemplateTaskDependancy : LoggedEntity
{
    [Column]
    public int NeededTaskId { get; set; }

    [Column]
    public int TaskId { get; set; }

    [Required]
    [ForeignKey("TaskId")]
    public virtual TemplateTask Task { get; set; }

    [Required]
    [ForeignKey("NeededTaskId")]
    public virtual TemplateTask NeededTask { get; set; }
}

[Table("TemplateTask")]
public class TemplateTask : LoggedEntity
{
    public ICollection<TemplateTaskDependancy> Dependancies;

    public ICollection<TemplateTaskDependancy> NeededTasks;

    public virtual Template Template { get; set; }
}

[Table("Template")]
public class Template : LoggedEntity
{
    public string Description { get; set; }
}

我的配置类如下

public class TemplateTaskConfiguration : EntityTypeConfiguration<TemplateTask>
{
    public TemplateTaskConfiguration()
    {
        HasMany(x => x.Dependancies)
            .WithRequired(d => d.Task)
            .HasForeignKey(d => d.TaskId)
            .WillCascadeOnDelete(false);

        HasMany(x => x.NeededTasks)
            .WithRequired(d => d.NeededTask)
            .HasForeignKey(d => d.NeededTaskId)
            .WillCascadeOnDelete(false);
    }
}

我的上下文如下

public class ApplicationDatabase : DbContext
{
    public DbSet<TemplateTask> TemplateTasks { get; set; }

    public DbSet<TemplateTaskDependancy> TemplateTaskDependancies { get; set; }

    public DbSet<Template> Templates { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Configurations.Add(new TemplateTaskConfiguration());
    }

    public void InitializeDatabase()
    {
            Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDatabase>());
    }
}

1 个答案:

答案 0 :(得分:2)

从字面上看,问题就是所描述的。 Dependancies是一个字段,而不是属性。只需将其定义为:

public virtual ICollection<TemplateTaskDependancy> Dependancies
{
     get;
     set;
}

它应该可以解决你的问题。