Reputation: 642
Im trying to save a new user into the users table with a new role. Here's the model and configuration.
When I insert the below entity, The role table gets populated with the new role, but the user entity is not being inserted.
`var userEntity = new User
{
Id = 0,
Active = true,
Firstname = "Fname",
Lastname = "Lname",
Password = "test",
Phonenumber = "2223334444",
Test = false,
Username = "[email protected]",
RoleId = 0
// Role = roleEntity
};
var roleEntity = new Role
{
Id = 0,
Name = "test role",
Active = true,
Users = new List<User>
{
userEntity
}
};
context.Role.Add(roleEntity);
await context.SaveChangesAsync();
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
public string Phonenumber { get; set; }
public bool Active { get; set; }
public bool Test { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public virtual ICollection<User> Users { get; set; }
public Role()
{
Users = new HashSet<User>();
}
}`
Here are the entity configurations.
`
public class RoleConfiguration : IEntityTypeConfiguration<Role>
{
public void Configure(EntityTypeBuilder<Role> builder)
{
builder.ToTable("Role");
builder.HasKey(r => r.Id);
builder.Property(r => r.Id).IsRequired().ValueGeneratedOnAdd();
builder.Property(r => r.Name).IsRequired().HasMaxLength(255);
builder.Property(r => r.Active).IsRequired();
builder.HasMany(r => r.Users)
.WithOne(u => u.Role)
.HasForeignKey(u => u.RoleId)
.OnDelete(DeleteBehavior.Restrict);
}
}
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("User");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).IsRequired().ValueGeneratedOnAdd();
builder.Property(u => u.Username).IsRequired().HasMaxLength(255);
builder.Property(u => u.Password).IsRequired();
builder.Property(u => u.Firstname).IsRequired().HasMaxLength(255);
builder.Property(u => u.Lastname).IsRequired().HasMaxLength(255);
builder.Property(u => u.Phonenumber).HasMaxLength(255);
builder.Property(u => u.Active).IsRequired();
builder.Property(u => u.Test).IsRequired();
builder.Property(u => u.RoleId).IsRequired();
builder.HasOne(u => u.Role)
.WithMany(r => r.Users)
.HasForeignKey(u => u.RoleId)
.OnDelete(DeleteBehavior.Restrict);
}
}`
Is there anything I'm doing wrong.
Thanks for your help.
Upvotes: 0
Views: 1656
Reputation: 642
I made a mistake by using
context.Entry(entity).State = EntityState.Added;
instead of
context.Add(entity);
that's why the related entities weren't being added.
Upvotes: 1