gpt4 book ai didi

c# - 未创建 Entity Framework 数据库

转载 作者:行者123 更新时间:2023-11-30 21:06:44 24 4
gpt4 key购买 nike

我首先在一个简单的 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: One or more validation errors were detected during model generation:

.Data.Edm.EdmEntityType: : EntityType 'Student' has no key defined. Define the key for this EntityType.System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Students� is based on type �Student� that has no keys defined.

最佳答案

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

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

public Guid StudentId { get; set; }

关于c# - 未创建 Entity Framework 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10950279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com