我正在创建一个简单的Web应用程序,允许已登录的用户存储未与其他用户共享的数据。
我无法将数据与用户关联。
该模型如下所示:
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; }
}
}
来自ASP.NET MVC5的生成的用户模型看起来像我的添加:
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; }
}
}
我想要实现的是,当登录用户进入创建电视节目网页并创建电视节目时,该特定电视节目和模型中的数据将被添加到用户。我有一个电视节目用户名单。
以下是我添加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);
}
我得到了用户,它可以正常运行并返回正确的用户。然后我得到电视节目列表,返回null。然后添加失败,因为tvshow列表为空。
如何向用户添加tvshows,以便我可以在特定用户的索引页面上显示它们?
答案 0 :(得分:2)
尝试直接访问users表并包含子集:
var id = User.Identity.GetUserId();
var user = db.Users.Include(u => u.TvShows).Single(u => u.Id == id);