Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

.net 4.5 - Non-static method requires a target. Entity Framework 5 Code First

I am getting the error "Non-static method requires a target." when I run the following query:

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

My entites are defines like this:

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

And my context is configured like this;

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

What have I done wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem boiled down to the query. My original question had this query:

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

Which wasn't quite accurate, I had in fact removed the error in an attempt to ask my question succinctly. The query was actually:

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

When the GetBusiness method returned null the error was thrown. Simply ensuring that I don't pass a null object into the expression made the error stop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...