They assigned me a project where I must create a sales system, but I want to use the Identity login and relate it to the sales table but I can not find the correct method
They assigned me a project where I must create a sales system, but I want to use the Identity login and relate it to the sales table but I can not find the correct method
You can do it this way. Let's give an example of your sale table
public class Venta
{
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime Fecha { get; set; }
public TimeSpan Hora { get; set; }
[Display(Name = "Producto")]
public int ProductoId { get; set; }
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual Producto Producto { get; set; }
}
As it is shown in the class, the ApplicationUserId attribute represents the user's Id and is of type string since Identity generates a Hash code and below makes the reference to the table with
public virtual ApplicationUser ApplicationUser
This way you tell EF that ApplicationUserId is a foreign key
now you are looking for the ApplicationUser class that Identity generates when you create an asp.net project, in my case I defined it in my context but it should normally be in your Models / IdentityModels folder and modify it so that you tell EF that a user has a collection of sales or purchases from the user's point of view
public class ApplicationUser : IdentityUser
{
public string Nombre { get; set; }
public string Apellidos { get; set; }
public bool Active { get; set; }
public virtual ICollection<Venta> Ventas { get; set; }
}
After doing your migration and giving a Rebuild to your project to see that everything is in order you add some code to your controller.
VentasController / Create
using Microsoft.AspNet.Identity;
if (ModelState.IsValid)
{
venta.ApplicationUserId = User.Identity.GetUserId();
db.Ventas.Add(venta);
db.SaveChanges();
return RedirectToAction("Index");
}
this is done in the controller since it is transaparent to the user. The application is the one who must take charge of collecting your ID and append it to the sale. I hope it helps you
Simple .. In the identitydbcontex in onmodelcreating you use links to your tables and you must also declare each one of them in the context ... you will not be able to make it simple if you have divided the contexts ... it works very well ... search a great example in Google that shows you a system of users groups and applications in identity and you will see how it is done .. it is very clear and simple ... that is your key ... makes your tests generate the migration and when reviewing it you are going to realize of apoco cone to go adjusting your code ... that is the way and of step you learn well how it works ef