53

我收到错误“非静态方法需要一个目标”。当我运行以下查询时:

var allPartners = DbContext.User
                           .Include(u => u.Businesses)
                           .Where(u => u.Businesses.Any(x => x.Id == currentBusinessId))
                           .ToList();

我的实体是这样定义的:

public class User : Entity
{
    public virtual List<Business> Businesses { get; set; }
}

public class Business : Entity
{
    public virtual List<User> Users { get; set; }
}

public class Entity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
}

我的上下文是这样配置的;

public class Context : DbContext, IDatabaseSession
{
    public DbSet<Business> Business { get; set; }
    public DbSet<User> User { get; set; }

    public Context()
        : base("DefaultConnection")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove
            <System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());

        modelBuilder.Entity<User>()
            .HasMany(u => u.Businesses)
            .WithMany(b => b.Users);
    }
}

我做错了什么?

4

1 回答 1

122

问题归结为查询。我原来的问题有这个查询:

var allPartners = DbContext.User
                       .Include(u => u.Businesses)
                       .Where(u => u.Businesses.Any(x => x.Id == currentBusinessId))
                       .ToList();

这不是很准确,实际上我已经删除了错误,试图简洁地提出我的问题。查询实际上是:

var currentBusiness = GetBusiness();
var allPartners = DbContext.User
                       .Include(u => u.Businesses)
                       .Where(u => u.Businesses.Any(x => x.Id == currentBusiness.Id))
                       .ToList();

GetBusiness方法返回时null,错误被抛出。只需确保我没有将null对象传递到表达式中,错误就会停止。

于 2012-11-08T19:02:01.460 回答