I am developing a login system in MVC, which includes the following entities: Subject, User and Roles The model of each entity is the following:
public partial class syssujetos
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SujetoId { get; set; }
[StringLength(15)]
public string cifdni { get; set; }
[StringLength(255)]
public string nombre { get; set; }
RECORTO LAS COLUMNAS QUE SON MUCHAS
public partial class sysusuarios
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UsuarioId { get; set; }
[StringLength(150)]
public string username { get; set; }
[StringLength(255)]
public string Pass { get; set; }
public bool? usuarioactivado { get; set; }
public string comentarios { get; set; }
public syssujetos Sujeto { get; set; }
}
public partial class sysroles
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int RolId { get; set; }
[Required]
[StringLength(50)]
public string nombre { get; set; }
[Required]
[StringLength(150)]
public string descripcion { get; set; }
public bool? desistema { get; set; }
public bool? deacceso { get; set; }
public ICollection<syssujetos> Sujetos { get; set; }
public sysroles()
{
Sujetos = new HashSet<syssujetos>();
}
}
Here the Controller
var idrol = Request.Form["idrol"];
//objUser.Sujetos.id
if (ModelState.IsValid)
{
// && a.Pass.Equals(objUser.Pass)
using (testModel db = new testModel())
{
//var usuario = db.Set<sysusuarios>();
syssujetos sujeto = new syssujetos();
sysroles rol = db.sysroles.Where(r=>r.nombre=="USUARIO").FirstOrDefault();
objUser.Sujeto.Roles.Add(rol);
rol = db.sysroles.Where(r => r.RolId.ToString() == idrol).FirstOrDefault();
objUser.Sujeto.Roles.Add(rol);
db.syssujetos.Add(objUser.Sujeto);
db.sysusuarios.Add(objUser);
db.SaveChanges();
return RedirectToAction("Home", "Index");
}
}
return View(objUser);
I am collecting the data correctly in the controller and apparently assigning well the values of the entities being ManytoMany between subject and roles and OneTomany between subject and users. But doing SaveChanges in the model gives me an error of SujetoId is Null, even though reviewing the value of the entity, which is also Identity as you see, this value corresponds to 0 and does not look Null. I do not understand why it determines that it is null.
Thank you.