I've created custom fields to the User:Identity class
public class User : IdentityUser
{
public virtual ICollection<Item> Items { get; set; }
}
where Item is a custom class
public class Item
{
public Guid Id { get; set; }
public string OwnerId { get; set; }
public string Name { get; set; }
[ForeignKey("OwnerId")]
public virtual User User { get; set; }
}
Then I use it in a controller method
[HttpPost]
public ActionResult AddToFavourite(bool check)
{
var user = UserManager.FindByIdAsync(User.Identity.GetUserId()).Result;
var item = new Item();
if (check)
user.Items.Add(item);
else
user.Items.Remove(item);
_context.CommitChanges();
return View();
}
Can anybody explain how to save this changes in database, please? I was trying to implement solution according to this, but unfortunately it still doesn't work for me. User entity is updated, but no changes saved in database.
UPDATE
public class ApplicationDbContext : IdentityDbContext<User>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{ }
public DbSet<Item> Items { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().HasMany(p => p.Items).WithMany().Map(mp => mp.ToTable("Favourite"));
}
}
public class Repository : IDisposable
{
private ApplicationDbContext _dbContext = new ApplicationDbContext();
public void CommitChanges() => _dbContext.SaveChanges();
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_dbContext.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}