[英]C# How to insert/update the parent and child data to the sql database using entity framework in asp.net mvc
[英]ASP.NET Core MVC & C# : insert data into database using Entity Framework
我正在尝试将数据从我的带有实体框架的 ASP.NET Core MVC 应用程序插入到我在本地主机上的 SQL Server 数据库中。
我的模型类如下所示:
public class Auto
{
public string Motorleistung { get; set; }
public string Lackierung { get; set; }
public string Felgen { get; set; }
public string Sonderleistungen { get; set; }
}
我已经在一个新文件夹( Services/AutoContext
类)中添加了DbContext
:
public class AutoContext : DbContext
{
DbSet<Auto> Autos { get; set; }
public AutoContext(DbContextOptions<AutoContext> options)
: base(options)
{
Database.EnsureCreated();
}
}
我在ConfigurateServices
方法中的Startup.cs
文件中添加了这部分:
public void ConfigureServices(IServiceCollection services)
{
var connectionString = "Server=localhost;Database=Auto;User Id=sa;Password=YourPassword123";
services.AddControllersWithViews();
services.AddDbContext<AutoContext>(o => o.UseSqlServer(connectionString));
}
我正在尝试使用带有方法的类扩展将 auto 中的属性插入到数据库中:
public static class AutoContextExtensions
{
public static void CreateSeedData(this AutoContext context)
{
var auto = new List<Auto>()
{
new Auto()
{
Motorleistung = "500 PS",
Lackierung = "Gelb",
Felgen = "Chrome",
Sonderleistungen = "Sitzheizung"
}
};
context.AddRange(auto);
context.SaveChanges();
}
}
我现在试图从Startup.cs
调用CreateSeedData
函数将数据传递到我的数据库中,例如:
Projectname.AutoContextExtensions.CreateSeedData();
它希望我给出一个参数。 我必须传递什么参数? (我从示例中提取了代码)
您需要一个上下文实例才能调用扩展方法。
有更多推荐的方法可以在 EFCore 中为数据库做种
1- 使用迁移来播种数据
然后 EF Core 迁移可以自动计算在将数据库升级到模型的新版本时需要应用哪些插入、更新或删除操作。
在 DBContext 中的 OnModelCreating
modelBuilder.Entity<Auto>().HasData( new Auto() {
Motorleistung = "500 PS",
Lackierung = "Gelb",
Felgen = "Chrome",
Sonderleistungen = "Sitzheizung"
});
然后添加一个新的迁移
2- 使用播种上下文
using (var context = new DataSeedingContext())
{
context.Database.EnsureCreated();
var testBlog = context.Blogs.FirstOrDefault(b => b.Url == "http://test.com");
if (testBlog == null)
{
context.Blogs.Add(new Blog { Url = "http://test.com" });
}
context.SaveChanges();
}
来自文档的警告
种子代码不应该是正常应用程序执行的一部分,因为这会在多个实例运行时导致并发问题,并且还需要应用程序具有修改数据库架构的权限。
CreateSeedData 是 AutoContext 类型的扩展方法。但是您正在调用类似 Projectname.AutoContextExtensions.CreateSeedData(); 的方法。 所以你需要传递autocontext类型的参数值。 您应该创建一个 AutoContext 类型的变量,然后 variablename.CreateSeedData() 使扩展方法像您期望的那样工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.