【问题标题】:Entity Framework database not being created未创建实体框架数据库
【发布时间】:2012-06-08 13:58:42
【问题描述】:

我首先在一个简单的 MVC3 应用程序中使用 EF4 代码。 上下文对象正在拾取正确的连接字符串,并调用初始化程序构造函数,就像 OnModelCreating 方法一样,但从未调用种子方法并且未创建数据库。任何想法为什么?

protected void Application_Start()
{
    Database.SetInitializer<SchoolContext>(new SchoolInitializer());
    SchoolContext context = new SchoolContext();
    context.Database.CreateIfNotExists();
    ...
}

public class SchoolInitializer : DropCreateDatabaseAlways<SchoolContext>
{
    public SchoolInitializer()
    {
    }
    protected override void Seed(SchoolContext context)
    {
        var students = new List<Student>
        {
            new Student {StudentId = Guid.NewGuid(), Name = "Carson" },
            new Student {StudentId = Guid.NewGuid(), Name = "Meredith" }
        };
        students.ForEach(s => context.Students.Add(s));
        context.SaveChanges();
    }
}

public class Student
{
    [Key]
    public Guid StudentId;
    public string Name;
}

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

配置:

<connectionStrings>
    <add name="SchoolContext" connectionString="Data Source=|DataDirectory|School.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

我认为抛出的异常只是抱怨数据库尚未创建:

[ModelValidationException:在模型生成期间检测到一个或多个验证错误:

.Data.Edm.EdmEntityType: : EntityType 'Student' 没有定义键。定义此 EntityType 的键。 System.Data.Edm.EdmEntitySet: EntityType: EntitySet “Students” 基于没有定义键的类型“Student”。

【问题讨论】:

  • 看来你应该为学生定义一个PK。我假设您的模型之间存在关系。此外,它明确指出“ModelValidationException”而不是“DatabaseValidationException”。 IT 是模型问题,而不是数据库问题。
  • 您确定要将 EF 与 sdf 文件一起使用而不是常规数据库吗?

标签: c# .net entity-framework exception-handling


【解决方案1】:

您的模型无效 - Student 实体没有定义键,并且在模型有效之前不会触发数据库创建。

您应该将访问器添加到您的StudentId。这将使模型有效并触发数据库创建

public Guid StudentId { get; set; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多