Seed data in code first Entity Framework - asp.net-mvc

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

Related

ASP.NET MVC "IDENTITY_INSERT is set to OFF"

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; }

Problem Insterting Multiple data on 2 tables

i am having problem on inserting multiple data in two tables.
Here is my code
Context Class
var userId = Convert.ToUInt32(user.Single(logon => logon.Type == CustomClaimTypes.UserId).Value);
/*Create access table for insert*/
var modules = p.Select(collection => new Accountcollection
{
AccountId = userId,
Amount = collection.Amount,
CashSource = collection.CashSource,
CollectionDate = collection.CollectionDate,
CreatedDatetime = DateTime.Now,
UpdatedDatetime = DateTime.Now,
}).ToList();
_context.Accountcollection.AddRange(modules);
var calendar_event = p.Select(collection => new Accountcalendarevents
{
AccountId = userId,
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
_context.Accountcalendarevents.AddRange(calendar_event);
_context.SaveChanges();
}
This is my collection model
public partial class Accountcollection
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public double? Amount { get; set; }
public string CashSource { get; set; }
public DateTime CollectionDate { get; set; }
public DateTime? CreatedDatetime { get; set; }
public DateTime? UpdatedDatetime { get; set; }
//public Accountcalendarevents Accountcalendarevents { get; set; }
public virtual Accountmaster Account { get; set; }
}
And this is my Caldendar Manager Events Model
public class Accountcalendarevents
{
[Key]
public long Id { get; set; }
public long AccountId { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string ThemeColor { get; set; }
public bool Isfullday { get; set; }
public string Status { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedDatetime { get; set; }
public long UpdatedBy { get; set; }
public DateTime UpdatedDatetime { get; set; }
}
The problem is when I insert only 1 data in works fine but if I try to insert 2 or more, i am getting this kind of exception
Exception i got
But, when I commented
var calendar_event = p.Select(collection => new Accountcalendarevents
{
//AccountId = userId, <-- when I comment this line
Subject = collection.CashSource,
Description = collection.CashSource,
Start = collection.CollectionDate,
End = collection.CollectionDate,
ThemeColor = "blue",
Isfullday = true,
Status = "1",
CreatedBy = userId,
CreatedDatetime = DateTime.Now,
UpdatedBy = userId,
UpdatedDatetime = DateTime.Now
}).ToList();
it works properly on multiple data insertion.
Hope you helped me with this. Thank you!

Need two separate tables but EF 6 is creating only one

I have a Contractor class and a Musicians Class which inherits the Contractor class. I am running migration and it will only build one Contractor table with Musicians fields included. I want a Contractor table and Musicians table that follows my domain models. It creates Instrument table correctly. Does this have something to do with the fact I am using inheritance on the classes?
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
}
public class Musician : Contractor
{
public Guid MusiciansId { get; set; }
public string WebsiteLink { get; set; }
public string YouTubeLink { get; set; }
public string SoundCloudLink { get; set; }
public string ReverbNationLink { get; set; }
public int YearsOfExperience { get; set; }
[DataType(DataType.Date)]
public DateTime NextDateAvailable { get; set; }
public Instrument Instrument { get; set; }
public int InstrumentId { get; set; }
public Contractor Contractor { get; set; }
public Guid ContractorId { get; set; }
}
My Migration script :
CreateTable(
"dbo.Contractor",
c => new
{
ID = c.Guid(nullable: false),
FirstName = c.String(),
LastName = c.String(),
Email = c.String(),
ZipCode = c.String(),
Phone = c.String(),
Description = c.String(),
CreateDate = c.DateTime(nullable: false),
SuspendDate = c.DateTime(nullable: false),
ImageData = c.Binary(),
ImageMimeType = c.String(),
ImageName = c.String(),
Suspended = c.Boolean(nullable: false),
UnionMember = c.Boolean(),
MusiciansId = c.Guid(),
WebsiteLink = c.String(),
YouTubeLink = c.String(),
SoundCloudLink = c.String(),
ReverbNationLink = c.String(),
YearsOfExperience = c.Int(),
NextDateAvailable = c.DateTime(),
InstrumentId = c.Int(),
ContractorId = c.Guid(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Contractor", t => t.ContractorId)
.ForeignKey("dbo.Instrument", t => t.InstrumentId, cascadeDelete: true)
.Index(t => t.InstrumentId)
.Index(t => t.ContractorId);
It is not a good idea to use inheritance in model classes.
You can add Type value for your Contractor and create another table for each type of contractor (Musician for example):
public enum ContractorType
{
Musician = 0
}
public class Contractor
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
public DateTime SuspendDate { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public string ImageName { get; set; }
public bool Suspended { get; set; }
public ContractorType contractorType { get; set; }
public Musician Musician { get; set; }
}
After doing some research the answer is: [Table] attribute above Musicians class.
http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type

Table only with foreign key in entity framework 6 (Fluent Api)

How to map foreign keys from two different table to one table in fluent Api?
My two model is like
public class Customer
{
[Key]
public string Userid { get; set; }
public string PassWord { get; set; }
public bool premium { get; set; }
}
public class Roles
{
[Key]
public string Name { get; set; }
public string Description { get; set; }
}
And 3rd table which has primary key of above table as foreign key?
public class CustomerRoles
{
public string RoleName { get; set; }
public string UserId { get; set; }
}
How to map in Fluent Api?
public class Customer
{
[Key]
public string Userid { get; set; }
public string PassWord { get; set; }
public bool premium { get; set; }
public ICollection<CustomerRole> CustomerRoles { get; set; }
}
public class Role
{
[Key]
public string Name { get; set; }
public string Description { get; set; }
public ICollection<CustomerRole> CustomerRoles { get; set; }
}
public class CustomerRole
{
public string RoleName { get; set; }
public string UserId { get; set; }
public Role Role { get; set; }
public Customer Customer { get; set; }
}
public class AppContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().HasMany(c => c.CustomerRoles).WithRequired(cr => cr.Customer);
modelBuilder.Entity<Role>().HasMany(r => r.CustomerRoles).WithRequired(cr => cr.Role);
modelBuilder.Entity<CustomerRole>().HasKey(cr => new { cr.RoleName, cr.UserId });
}
}
PS: Class name should not be plural, it can confuse with array property.
update how to use it
static void Main(string[] args)
{
using (var ctx = new AppContext())
{
Customer customer = new Customer { Userid = "A" };
ctx.Customers.Add(customer);
Role role1 = new Role { Name = "Role1" };
ctx.Roles.Add(role1);
Role role2 = new Role { Name = "Role2" };
ctx.Roles.Add(role2);
customer.CustomerRoles = new[]
{
new CustomerRole { Customer = customer, Role = role1 },
new CustomerRole { Customer = customer, Role = role2 },
};
ctx.SaveChanges();
}
}

EF5 Migrations throwing error on simplemembership seed

Error:
No mapping exists from object type eTrail.Models.Global.Address to a known managed provider native type.
The code that is throwing the error:
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
Address = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}
My User.cs Model:
public class User : IAuditInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public Address UserAddress { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public ICollection<Role> Roles { get; set; }
public string ImageName { get; set; }
public User()
{
UserAddress = new Address();
Roles = new List<Role>();
}
}
The Address Model:
public class Address
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Street { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string PhoneHome { get; set; }
public string PhoneCell { get; set; }
public string PhoneOther { get; set; }
public string FaxNumber { get; set; }
}
Any idea why I am getting this error? Both Model classes are in my DbContext class as DbSet and DbSet.
You used the wrong property name when you created the new user account. You used Address instead of UserAddress. Make the following change under the comment I added to the code.
if (!WebSecurity.UserExists("me"))
{
WebSecurity.CreateUserAndAccount(
"me",
"password", new
{
FirstName = "Firstname",
LastName = "Lastname",
Email = "me#me.com",
//Changed Address to UserAddress
UserAddress = new Address
{
Street = "123 Stree",
Street2 = "",
City = "CityVille",
State = "UT",
Zip = "99999",
Country = "USA",
PhoneCell = "111.111.1111"
},
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
ImageName = ""
});
}

Resources