这是我的数据库表
CREATE TABLE [dbo].[MyClass] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Criteria] NCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
SET IDENTITY_INSERT MyClass ON;
insert into MyClass(Id, Criteria) values('1', 'Value1');
insert into MyClass(Id, Criteria) values('2', 'Value2');
连接字符串
<add name="EFDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=MyTableName;Integrated Security=True" providerName="System.Data.SqlClient" />
和EFDbContext类
public class EFDbContext : DbContext {
public EFDbContext()
: base("EFDbContext") {
}
public DbSet<MyClass> MyClasses { get; set; }
}
但是,'count'的值始终为零。
public class MyController : Controller
{
public ActionResult Index() {
var db = new EFDbContext();
var firstValue = db.MyClasses.FirstOrDefault(x => x.Id > 1);
var count = db.MyClasses.Count();
return View();
}
}
编辑: 我试过var count = db.MyClasses.ToList()。Count();但仍然返回零
答案 0 :(得分:3)
使用此:
List<MyClasses> classList = db.MyClasses.ToList();
int count = classList.Count();
答案 1 :(得分:0)
检查代码中的这一行
SET IDENTITY_INSERT **SqaCriterion** ON; //It should be **SqlCriterion**
insert into MyClass(Id, Criteria) values('1', 'Value1');
insert into MyClass(Id, Criteria) values('2', 'Value2');