dbContext不更新数据库 [英] DbContext not updating database

查看:121
本文介绍了dbContext不更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我保存对DbContext的更改时,它不会更新数据库。

When I save changes to DbContext, it doesn't update my database. No errors either.

是的,输入的表单数据已填写。是的,连接字符串正确,我知道这一点,因为我可以从数据库中很好地检索数据。如果是相关的,那就是多对多的关系。

Yes, the incoming form data is filled. Yes, the connection string is correct, I know this because I'm able to retrieve data from the database perfectly fine. If it's of relevance, it's a many-to-many relationship.

就您而言,路线图就像是一篇文章,可以与许多标签相关联。

A roadmap is like an article as far as you're concerned which can be associated with many tags.

    public static class RoadmapService
    {
        static ConkerDbEntities dbContext;
        public static void createDbContext(ConkerDbEntities _dbContext)
        {
            dbContext = _dbContext;
        }

        public static void addToDatabase(Form form)
        {
            Roadmaps roadmap = new Roadmaps { RoadmapTitle = form.title, 
                                              RoadmapSummary = form.summary, 
                                              RoadmapBody = form.body };

            var tags = new Tags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                tags[i] = new Tags();
                tags[i].TagId = form.tags[i];
            }

            var roadmapTags = new RoadmapTags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
            }

            dbContext.AddRange(roadmapTags);
            dbContext.SaveChangesAsync();
        }
    }
}

在创建dbcontext的位置,此是Startup.cs的构造函数。

Where dbcontext is created, this is the constructor of Startup.cs

        public static SearchEngine engine;
        public static ConkerDbEntities dbContext;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            dbContext = new ConkerDbEntities();

            RoadmapService.createDbContext(dbContext);
            engine = new SearchEngine(dbContext);

        }

我没有错误,也没有任何错误添加到数据库。我可能在这里做了根本上错误的事情。

I get no errors, and there's nothing added to the database. I'm probably doing something fundamentally wrong here. Thanks in advance.

推荐答案

您正在使用异步编程,但是您的方法不是异步的。

You are using async programming, but your method is not async.

使用 dbContext.SaveChangesAsync(); 当您具有异步方法时,请使用 dbContext.SaveChanges(); when不是异步。

use dbContext.SaveChangesAsync(); when you have async methods, use dbContext.SaveChanges(); when is not async.

此外,您使用的是静态类,如果您使用的是依赖注入,则情况并非如此。 DI将处理对象的生命周期。

Also, you are using static classes, this should not be the case if you are using dependency injection. DI will handle the life cycle of your objects.

您的类未按应定义的方式定义,存在一些格式错误,并且应如下所示:

Your class is not defined as should be, you have some format errors, and should look something like this:

public class RoadmapService
{
    private readonly ConkerDbEntities _dbContext;

    public RoadmapService(ConkerDbEntities dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task AddToDatabase(Form form)
    {
        Roadmaps roadmap = new Roadmaps {
            RoadmapTitle = form.title, 
            RoadmapSummary = form.summary, 
            RoadmapBody = form.body 
        };

        var tags = new Tags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            tags[i] = new Tags();
            tags[i].TagId = form.tags[i];
        }

        var roadmapTags = new RoadmapTags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
        }

        _dbContext.AddRange(roadmapTags);
        _dbContext.SaveChangesAsync();
    }
}

然后在您的控制器中,您可以按原样使用服务

Then in your controller you can use your service as is

public class OrdersController : Controller
{
    private readonly RoadmapService _roadmapService;

    public OrdersController(RoadmapService roadmapService)
    {
        _roadmapService = roadmapService;
    }

    [HttpGet]
    [Route("api/[controller]/{folio}")]
    public async Task<IActionResult> Status(string folio)
    {
        await _roadmapService.AddToDatabase(something);
        return Ok();
    }
}

我还建议您研究linq以及如何使用可以避免这些使用select for foreach周期,请检查默认的净核心编码标准

I also would recommend to study about linq and how you can avoid those foreach cycles using select, check the default net core coding standards.


我很好奇,LINQ会在这种情况下提供
而不是常规for循环的性能优势吗?

I'm curious, would LINQ provide any performance benefits in this case vs just a regular for loop?

更多关于代码的可读性和可维护性,在答案中,我已经放置了指向文章的链接,其中的解释更好,您正在创建技术债务在您的代码中,您正在初始化数组并填写g,处理索引等...,但是简化为:

It is more about the readability and maintainability of your code, in the answer I already put a link to a post where is better explained, you are creating technical debt in your code, you are initializing arrays and filling them, handling indices and more... , but it reduces to this:

还有什么更容易阅读的?此:

What is more easy to read? this:

public async Task AddToDatabase(Form form)
{
    Roadmaps roadmap = new Roadmaps {
        RoadmapTitle = form.title, 
        RoadmapSummary = form.summary, 
        RoadmapBody = form.body 
    };

    var tags = new Tags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        tags[i] = new Tags();
        tags[i].TagId = form.tags[i];
    }

    var roadmapTags = new RoadmapTags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
    }

    _dbContext.AddRange(roadmapTags);
    _dbContext.SaveChangesAsync();
}

或此

    public async Task AddToDatabase(Form form)
    {
        var roadmap = new Roadmap {
            RoadmapTitle = form.title, 
            RoadmapSummary = form.summary, 
            RoadmapBody = form.body 
        };

        var roadmapTags = form.Tags
            .Select(tagId => new Tag        // First we take our form.tags and convert it to Tag objects
            {
                TagId = tagId
            })
            .Select(tag => new RoadmapTags  // Then we take the result of the previous conversion and we 
            {                               // transform again to RoadmapTags, we even could do this in one pass
                Roadmap = roadmap,          // but this way is more clear what the transformations are
                Tag = tag
            })
            .ToList();

        _dbContext.AddRange(roadmapTags);
        await _dbContext.SaveChangesAsync();
    }

如果您刚刚开始学习编程,那么在您感到更舒适之前,可以忽略它与 for foreach while 和其他控制结构。这是结构编程,它本身就是一个主题。

If you just started learning programming, you could ignore this until you are more confortable with the for, foreach, while and other control structures. This is structure programming, and it is a topic by itself.


我也该如何将roadmapService对象传递给Controller

Also how would I pass the roadmapService object to the Controller constructor, I've just never seen that.

这就是依赖注入的魔力,只需让系统为您创建对象,您只需要询问类型即可。

That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

这也是一个大话题,您应该检查我以前指向microsoft文档的链接,但是基本上,要做的是将类定义为依赖项,因此,当您请求类时,系统本身会检查依赖项以及该对象的依赖项,直到解析所有依赖关系树为止。

This is also a big topic, you should check my previous link to the microsoft documentation, but basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

这样,如果您的类中还需要一个依赖项,则可以直接添加,但是您不需要修改所有使用该类的类。

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

要在控制器中使用此功能,请查看官方文档,您只需将依赖项添加到构造函数中,然后赢取!基本上是两个部分:

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

在您的Startup.class中添加

Add in your Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}

然后在您的控制器中:

public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }

这篇关于dbContext不更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆