Reputation: 897
I am creating a simple web application that allows a logged user to store data not shared with other users.
I am having trouble associating the data to the user.
The model looks like this:
namespace TvShowsDb.Models
{
public class TvShow
{
public int TvShowID { get; set; }
public string TvShowName { get; set; }
public string LastEpisodeSeen { get; set; }
public string Comment { get; set; }
public bool SeenAll { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateLastEdited { get; set; }
}
}
And the generated user model from ASP.NET MVC5 looks like this with my additions:
namespace TvShowsDb.Models
{
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public IList<TvShow> TvShows { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<TvShowsDb.Models.TvShow> TvShows { get; set; }
}
}
What I am trying to achieve is that when a logged in user goes to the create tv show web page and creates a tvshow then that specific tv show and the data from the model gets added to the user. I have a list in the user with tv shows.
Here is a picture of how the database looks:
Here is the code for when I add a tvshow:
// POST: TvShows/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TvShowID,TvShowName,LastEpisodeSeen,Comment,SeenAll,DateAdded,DateLastEdited")] TvShow tvShow)
{
if (ModelState.IsValid)
{
var user = UserManager.FindById(User.Identity.GetUserId());
IList<TvShow> tvshows = user.TvShows;
user.TvShows.Add(tvShow);
// db.TvShows.Add(tvShow);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tvShow);
}
I get the user, that works and returns the correct user. Then I get the tv show list, that returns null. Then the adding fails since the tvshow list is null.
How do I go about adding tvshows to the user so that I can show them on the index page for that particular user?
Upvotes: 0
Views: 69
Reputation: 12304
Try accessing the users table directly and including the child collection:
var id = User.Identity.GetUserId();
var user = db.Users.Include(u => u.TvShows).Single(u => u.Id == id);
Upvotes: 2