Entity Framework won't persist data in SQL Express (MDF)

后端 未结 4 1169
醉酒成梦
醉酒成梦 2021-01-02 03:20

I was developing an application using Entity Framework and storing data in a .mdf database. My code can read the data, apparently it can save too, but only apparently. It ge

4条回答
  •  攒了一身酷
    2021-01-02 03:41

    A few things leap to mind:

    • double/treble-check your connection string; are you really talking to the file that you think you are?
    • are you using transactions anywhere and not committing them?
    • do you have the mdf file set to "Copy Always" (or whatever it is).... i.e. are you constantly overwriting the mdf whenever you hit build/play?

    Also - I don't think it'll matter in this case, but to verify data you should use a different entities/data-context:

    using (DatabaseEntities e = new DatabaseEntities()) {
        for (int i = 0; i < 50; i++) {
            User u = new User();
            u.Nome = "User" + i.ToString();
            e.AddToUser(u);
        }
        int c = e.SaveChanges(true);
    }
    using (DatabaseEntities e = new DatabaseEntities()) {
        List us = e.User.Where(x => x.ID < 50).ToList();
        foreach (User u in us)
            Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome);
    }
    Console.ReadKey();
    

    Like I said - I doubt it'll matter here, but worth checking...

提交回复
热议问题