简体   繁体   中英

ASP.NET Core MVC & C# : insert data into database using Entity Framework

I am trying to insert data from my ASP.NET Core MVC application with Entity Framework to my SQL Server database on localhost.

My model class looks like this:

public class Auto
{
    public string Motorleistung { get; set; }
    public string Lackierung { get; set; }
    public string Felgen { get; set; }
    public string Sonderleistungen { get; set; }
}

I already added the DbContext in a new folder ( Services/AutoContext class):

public class AutoContext : DbContext
{
    DbSet<Auto> Autos { get; set; }

    public AutoContext(DbContextOptions<AutoContext> options)
        : base(options)
    {
        Database.EnsureCreated();
    }
}

I added this part to the Startup.cs file in the ConfigurateServices method:

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));
}

I am trying to use a class extension with a method to insert properties from auto into the DB:

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();
    }
}

I am now trying to call the CreateSeedData function from the Startup.cs to pass the data into my database like:

Projectname.AutoContextExtensions.CreateSeedData();

It expects me to give a parameter. What parameter do I have to pass? (I extracted the code from a sample)

You need an instance of the context to be able to call the extension method.

There are more recommended ways to seed the database in EFCore

1- Use migrations to seed the data

Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.

in OnModelCreating in the DBContext

modelBuilder.Entity<Auto>().HasData( new Auto()  {
                    Motorleistung = "500 PS",
                    Lackierung = "Gelb",
                    Felgen = "Chrome",
                    Sonderleistungen = "Sitzheizung"
                });

Then Add a new migration

2- Use seeding context

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();
}

a Warning from the docs

The seeding code should not be part of the normal app execution as this can cause concurrency issues when multiple instances are running and would also require the app having permission to modify the database schema.

For more details check the documentation along with full sample project

CreateSeedData is an extension method for AutoContext type.But you are calling method like Projectname.AutoContextExtensions.CreateSeedData(); so you need to pass the parameter value of type autocontext. You should create a variable with AutoContext type ,Then variablename.CreateSeedData() for extension method to work like you expect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM