简体   繁体   中英

Empty dbSet in ApplicationDbContext

In mvc5 application i'm create class in folder "Models":

public class Code
{
    [Key]
    public Guid Id { get; set; }
    public string UserId { get; set; }
}

And make migration.

Also i got class(context, autogenerated):

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    public DbSet<Code> Codes { get; set; }
}

In one of my controllers i wrote method:

using (var db = new ApplicationDbContext())
{
    var manager =
        new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
    var user = manager.FindById(User.Identity.GetUserId());
    Code codeD = new Code();
    codeD.Id = Guid.NewGuid();
    codeD.UserId = user.Id;
    db.Codes.Add(codeD);
    db.SaveChanges();
}

But every time when i do it, db.Codes got 0 items. 在此输入图像描述

But in my Data Base changes saved and i got this items: 在此输入图像描述

Did anyone know reason of such phenomenon? I can't reach items from Data base, but im free to save new items. Did someone know, how gets all "Codes" from my Database?

I used generated mvc5 project, so ApplicationUserDbContext generated automaticaly.

Kind regards.

Moving to answer for future searchers:

Before you can see the results of a query in Entity Famework, you have to materialize the view. EF returns IQueryable from most of its' methods. IQueryable actually is a mechanism that allows EF to continue to build the sql needed to get the needed data from the db. This is why when you are on the debugging view it shows something like Select [Columns] From [table] as Extent1 when viewing the DbSet. It is just SQL that has yet to be executed. When you actually try accessing a property or an object from the set, EF will send the query to the db and materialize the results.

Materializing the results should be a natural occurrence for the most part. If you need a list of Users, you should call the ToList() method for the results to be materialized. If you only want a single record, you should use the FirstOrDefault() method which will materialize a single record or null if nothing is found.

Example:

//Materializing a collection of users
public ActionResult Users() 
{
    //The DbContext has been initialized elsewhere
    var users = _db.Users.Where(user => user.IsActive).ToList();

    return View(users);
}

//Materializing a single record
public ActionResult User(int userId)
{
    var user = _db.Users.FirstOrDefault(user => user.Id == userId && user.IsActive);
    if (user == null) return HttpNotFound();

    return View(user);
}

It is important to note that EF's loading of entities only when requested can cause issues if you dispose of the context and then try to access the results in the view. This will cause an exception because there is no context that can load the results for you.

You may want to check if you have the correct Connection String in your Web.config file. This will of course vary, but you should have something along the lines of:

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=MyDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

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