非静态方法需要一个目标.实体框架 5 代码优先 [英] Non-static method requires a target. Entity Framework 5 Code First
本文介绍了非静态方法需要一个目标.实体框架 5 代码优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到错误非静态方法需要目标."当我运行以下查询时:
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();
我的实体定义如下:
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);
}
}
我做错了什么?
推荐答案
问题归结为查询.我原来的问题有这个查询:
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();
当 GetBusiness
方法返回 null
时,错误被抛出.只需确保我没有将 null
对象传递到表达式中,错误就会停止.
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.
这篇关于非静态方法需要一个目标.实体框架 5 代码优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文