0
我創建了一個DataContext。實體框架DataContext返回空值
namespace Attendance.DataAccess.DAL
{
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Attendance.DataAccess.Models;
public class AttendanceContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public AttendanceContext()
: base("AttendanceContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
我已經創建了一個配置。
namespace Attendance.DataAccess.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Attendance.DataAccess.Models;
using Attendance.DataAccess.DAL;
internal sealed class Configuration : DbMigrationsConfiguration<AttendanceContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(AttendanceContext context)
{
context.Persons.AddOrUpdate(
p => p.FirstName,
new Person { FirstName = "Andrew Peters" },
new Person { FirstName = "Brice Lambson" },
new Person { FirstName = "Rowan Miller" }
);
}
}
}
我已經創建了初始遷移。
namespace Attendance.DataAccess.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Person",
c => new
{
Id = c.Int(nullable: false, identity: true),
FirstName = c.String(),
LastName = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.Person");
}
}
}
我已經創建了一個簡單的API控制器。
namespace Attendance.WebApi.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Attendance.DataAccess.Models;
using Attendance.DataAccess.DAL;
using System.Data.Entity;
public class PersonController : ApiController
{
// http://localhost/Attendance.WebApi/api/person
public IEnumerable<Person> GetAllPersons()
{
AttendanceContext db = new AttendanceContext();
var persons =
from person
in db.Persons
select person;
// this is always an empty array
// I.e. the web browser displays <ArrayOfPerson/>
return persons.ToList();
}
}
}
我已經配置如下:
<connectionStrings>
<add name="AttendanceContext"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AttendanceLocal;Integrated Security=SSPI;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
我也直接查詢數據庫,使用服務器資源管理器和對象資源管理器。數據庫在Person表中有行。爲什麼這些行不顯示在實體框架DataContext Person中?