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

查看:27
本文介绍了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(); 当不是异步时.

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 以及如何使用选择避免那些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?

更多的是关于代码的可读性和可维护性,在答案中我已经放了一个链接到一个更好解释的帖子,你正在创建 技术债务 在您的代码中,您正在初始化数组并填充它们,处理索引等等...,但它简化为:

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

如果你刚开始学习编程,你可以忽略这一点,直到你对 forforeachwhile 和其他控制结构.这是结构化编程,它本身就是一个主题.

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 对象传递给控制器构造函数,我只是从未见过.

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.

这也是一个很大的话题,你应该查看我之前的微软文档链接,但基本上,你要做的就是将类定义为依赖项,因此,当你要求一个时,系统本身会检查依赖项,以及该对象的依赖关系,直到解析所有依赖关系树.

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天全站免登陆