Tried to make a One-to-Zero-or-One relationship between User and Artist and chose ArtistId to both Primary and Foreign Key but when it comes to inserting data, the database won't let me
Error
Cannot insert explicit value for identity column in table 'Artists' when IDENTITY_INSERT is set to OFF
Models
public class User
{
[Key]
public int UserId { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[MinLength(3)]
[MaxLength(255)]
public string Password { get; set; }
[Required]
public byte RoleId { get; set; }
public DateTime RegisterDate { get; set; }
public Artist Artist { get; set; }
}
public class Artist
{
[ForeignKey("User")]
public int ArtistId { get; set; }
public string ProfilePhoto { get; set; }
public string Bio { get; set; }
public User User { get; set; }
}
Action in Controller
public ActionResult Register(ArtistRegisterViewModel viewModel)
{
if (ModelState.IsValid)
{
if (viewModel.ConfirmPassword == viewModel.User.Password)
{
var user = new User
{
Email = viewModel.User.Email,
Password = viewModel.User.Password,
RegisterDate = DateTime.Now,
RoleId = RoleType.Artist
};
var artist = new Artist
{
Bio = viewModel.Artist.Bio,
ProfilePhoto = viewModel.Artist.ProfilePhoto,
};
_context.Users.Add(user);
_context.Artists.Add(artist);
_context.SaveChanges();
return Content("New Artist Created");
}
}
return View("Register", viewModel);
}
Annotate ArtistId so that EF does not create an identity for the PK:
[ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ArtistId { get; set; }
Related
I am using code-first Entity Framework in my ASP.NET MVC project
I have these tables
User
public class User:IBaseEntity
{
public User()
{
UserRoles = new List<UserRole>();
}
public int ID { get; set; }
public int RoleId { get; set; }
public string Email { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Company { set; get; }
public string Address1 { set; get; }
public string Address2 { set; get; }
public string City { set; get; }
public string PostalCode { set; get; }
public string Country { set; get; }
public string State { set; get; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
Role
public class Role : IBaseEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public bool Active { set; get; }
public DateTime? CreatedOn { set; get; }
public DateTime? DeletedOn { set; get; }
}
UserRole
public class UserRole : IBaseEntity
{
public int ID { get; set; }
public int UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
IBaseEntity
public interface IBaseEntity
{
int ID { get; set; }
}
I need seed data User with UserRole
How can I put UserRole in method create User?
public void CreateRoles(CMSDbContext context)
{
if (context.Roles.Count() == 0)
{
List< Role> listRole = new List<Role>()
{
new Role()
{
RoleName = "Admin",
Active = true,
CreatedOn = DateTime.Now
},
new Role()
{
RoleName = "User",
Active = true,
CreatedOn = DateTime.Now
}
};
context.Roles.AddRange(listRole);
context.SaveChanges();
}
}
public void CreateUser(CMSDbContext context)
{
if (context.Users.Count() == 0)
{
List<User> listUser = new List<User>()
{
new User()
{
FirstName = "David",
LastName = "Lima",
Active = true,
Email = "admin#domain.com",
Address1 = "New York",
Address2 = "Chicago",
Company = "Test",
CreatedOn = DateTime.Now,
PostalCode = "123456",
State = "Test",
City = "test",
UserRoles =???
Password = CMS.Common.HashMD5.CreateMD5("12356")
}
};
context.Users.AddRange(listUser);
context.SaveChanges();
}
}
}
Please focus on method CreateUser have property UserRole, not sure what I can put here. I also create some roles in Role table (admin, user)
I am getting stuck at this point.
Any help will be appreciated
Thanks all
I have 2 models, Artist and Album.
Artist have a collection of albums.
Album have a foreigm key to Artist (int artistId).
Now in my site you get to select the album for edition from its artist,
and when I send the album back to the controller, its artistId always 0 (default value of int) and I failed to save the album, because there is no such artist with 0 id. How I'm losing the id of the artist?
the artist
public class Artist
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string NickName { get; set; }
public string Website { get; set; }
public string Facebook { get; set; }
public string Twitter { get; set; }
public string Wikipedia { get; set; }
public string Background { get; set; }
public long StartYearActivity { get; set; }
public virtual ICollection<Album> Albums { get; set; }
public DateTime Birthdate { get; set; }
}
the album
public class Album
{
public int Id { get; set; }
public int ArtistId { get; set; }
public string Genre { get; set; }
public string Wikipedia { get; set; }
public List<Song> Songs { get; set; }
public string Name { get; set; }
public int NumOfSongs { get { return this.Songs != null ? this.Songs.Count : 0; } }
public int Year { get; set; }
}
the save method for album when the artist id is null:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditAlbum([Bind(Include = "Id,Genre,Wikipedia,Name,Year")] Album album)
{
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(album);
}
What am I doing wrong?
Please look at my sample code below:
public class LoginModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class RegisterModel
{
[Key]
public int RegisterId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
}
There are many records in the cart table added by many users.
But i want to show the own record of a user from the cart table if he is logged in..how can I do this??
You have to insert a foreign-key property to your Cart class:
public class UserModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
public virtual UserModel User { get; set; } // <-- added
}
Then you can use LINQ to query the Cart-items for a specific user:
var cartItems = dbContext.Cart.Where(a => a.User == loggedInUser);
var query = from a in db.Pages
where a.title.Contains(myTitle)
select a;
var item=query.FirstOrDefault();
if(item!=null)
return View(item);
else
return View("NotFound");
I have three entity classes. what I am trying to do is to insert data into User table and insert the data at the same time to the table called Company. and Owner
Here is the my code: (as title mentioned that I am getting insert error)
public class User : BaseEntity
{
[Key]
public int Id { get; set; }
public virtual Company.Company Company { get; set; }
public virtual Owner.Owner Owner { get; set; }
public string Username { get; set; }
...........
}
public class Company : BaseEntity
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
public string Explanation { get; set;
...........
}
public class Owner:BaseEntity
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public string NameSurname { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
...........
public virtual User User { get; set; }
}
User usr=new User {
usr.NameSureName = user.NameSureName;
usr.Email = user.Email;
...........
};
var company = new Company
{
CompanyMemberShipType = CompanyMemberShipType.Free,
};
var owner = new Owner
{
CellPhone = user.CellPhone,
Email = user.Email,
NameSurname = user.NameSureName
};
usr.Company = company;
usr.Owner = owner;
var userresult = _userService.Insert(usr);
I'm using asp.net mvc 4, EF, codefirst to make a many to many relation to a users and roles system
the user model:
public class User
{
#region properties
[Key]
public Int32 Id { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
[Required]
public String Email { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime? LastLogin { get; set; }
[ForeignKey("RoleId")]
public virtual ICollection<Role> Roles { get; set; }
#endregion //properties
#region constructors
public User()
{
Roles = new HashSet<Role>();
LastUpdate = DateTime.Now;
CreationDate = DateTime.Now;
}
#endregion //constuctors
}
the role model:
public class Role
{
[Key]
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
[ForeignKey("UserId")]
public virtual ICollection<User> Users { get; set; }
public Role()
{
Users = new HashSet<User>();
CreationDate = DateTime.Now;
LastUpdate = DateTime.Now;
}
}
the context:
public class UserManagementContext : Context, IContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public UserManagementContext() {
Database.SetInitializer<UserManagementContext>(null);
}
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
}
}
When the database tables are generated the tables users, roles and userroles are there. Then I make a record in users, one in roles and one in userroles to connect those. The userroles table has two columns RoleId and UserId.
Then I try to load the roles of a user like this:
public String[] GetRoles(String userName)
{
//var user = ConcreteContext.Users.Include("Roles").Where(u => u.UserName == userName).FirstOrDefault();
var users = ConcreteContext.Users.Include(u => u.Roles);
var user = users.FirstOrDefault();
var roles = from r in user.Roles
select r.Name;
return roles.ToArray();
}
But the line with var users = ConcreteContext.Users.Include(u => u.Roles); raises the next error:
System.Data.SqlClient.SqlException: Invalid object name 'dbo.RoleUsers'.
If I change de table name of UserRoles to RoleUsers when de database is created (by using m.ToTable(RoleUsers) ), I get a lot of different errors about wrong field names.
Anyone an idea what I'm missing here?
Thanks in advance,
Willem
Any reason why you have to use the Fluent API?
You can map Many-to-many like this with data attributes:
public class User
{
[InverseProperty( "Users" )]
public virtual ICollection<Role> Roles {get;set;}
}
public class Role
{
[InverseProperty( "Roles" )]
public virtual ICollection<User> Users {get;set;}
}
This will do what I needed:
public class User
{
#region properties
[Key]
public Int32 Id { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
[Required]
public String Email { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime? LastLogin { get; set; }
[InverseProperty("Users")]
public virtual ICollection<Role> Roles { get; set; }
#endregion //properties
#region constructors
public User()
{
LastUpdate = DateTime.Now;
CreationDate = DateTime.Now;
}
#endregion //constuctors
}
public class Role
{
[Key]
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
[InverseProperty("Roles")]
public virtual ICollection<User> Users { get; set; }
public Role()
{
CreationDate = DateTime.Now;
LastUpdate = DateTime.Now;
}
}
public class UserManagementContext : Context, IContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public UserManagementContext() {
Database.SetInitializer<UserManagementContext>(null);
}
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
}
}