How we add foreign key in asp.net identity MVC Project - asp.net-mvc

ApplicationUser Class which inherit with IdentityUser
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
public virtual Patient Patients { get; set; }
public int PatientID { get; set; }
}
Patient Class
public class Patient
{
[Key]
public int PatientID { get; set; }
public string ProfilePicture { get; set; }
public string FName { get; set; }
public DateTime BirthDate { get; set;}
public string City { get; set; }
public string Country { get; set; }
}
Controller
public async Task<ActionResult> RegisterPatient(RegisterViewModel model)
{
MYDb db = new MYDb();
Patient pt = new Patient();
pt.BirthDate = model.BirthDate;
pt.City = model.City;
pt.Country = model.Country;
pt.ProfilePicture = model.ProfilePicture;
pt.FName = model.FName;
int Pat_id = model.PatientID;
if (ModelState.IsValid)
{
ApplicationUser myuser = new ApplicationUser();
model.CreatedOn = DateTime.Now;
model.IsActive = true;
myuser.PatientID = Pat_id;
if (ModelState.IsValid)
{
var user = model.GetUser();
db.Patients.Add(pt);
db.SaveChanges();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var idManager = new IdentityManager();
idManager.AddUserToRole(user.Id, model.User_type);
//await db.SaveChangesAsync();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View();
}
i want to make relationship b/w Patient and ApplicationUser first i
add record in patient then "Patient_ID" used as a foreign key in
ApplicationUser Table but when add data i face this type of error
Error
Note : data save in Patient table but not in ApplicationUser table because ApplicationUser not get "PatientID" therefore conflict occurred in DB.
I hope this is much clear and its not easy to solve :(

In Applicatin User Model Write done this :
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
[ForeignKey("PatientID")]
public virtual Patient Patients{ get; set; }
}
I think it will work.

Related

How to put a view in another view in asp.net MVC?

Here I have a MainController in which I have two actions named Create and PhotoUpload. Here is the code for Create action.
// GET: Main/Create
public ActionResult Create()
{
return View();
}
// POST: Main/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Email,Password,FirstName,LastName,Gender,Birthday,ProfileImage,AboutUser")] User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Here is the code for PhotoUpload action.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PhotoUpload(PhotoModel model)
{
if (model.PhotoFile.ContentLength > 0)
{
var fileName = Path.GetFileName(model.PhotoFile.FileName);
var filePath = Server.MapPath("/Content/Users/Images");
string savedFileName = Path.Combine(filePath, fileName);
model.PhotoFile.SaveAs(savedFileName);
}
return View(model);
}
public ActionResult PhotoUpload()
{
return View();
}
And these are the User and Photo models. This is the User Model
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Friends = new HashSet<Friend>();
this.Friends1 = new HashSet<Friend>();
this.Photos = new HashSet<Photo>();
}
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public System.DateTime Birthday { get; set; }
public string ProfileImage { get; set; }
public string AboutUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Friend> Friends { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Friend> Friends1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Photo> Photos { get; set; }
}
This is the PhotoModel
public class PhotoModel
{
[Required]
public HttpPostedFileBase PhotoFile { get; set; }
}
And this is what I am getting as a view now. This is my /Main/Create View
And this is my /Main/PhotoUpload View
Now I want to put this PhotoUpload view instead of ProfileImage thing inside my Create View. Where do I change this and how?
You should use a ViewModel as that's the recommended practice for transferring data to and from views, in this case you can do the following as #StephenMuecke commented
ViewModel
public class UserViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public System.DateTime Birthday { get; set; }
public string ProfileImage { get; set; }
public string AboutUser { get; set; }
[Required]
public HttpPostedFileBase PhotoFile { get; set; }
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserViewModel model)
{
if (ModelState.IsValid)
{
AddUser(model);
SavePhoto(model.PhotoFile);
return RedirectToAction("Index");
}
return View(user);
}
private void SavePhoto(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var filePath = Server.MapPath("/Content/Users/Images");
string savedFileName = Path.Combine(filePath, fileName);
file.SaveAs(savedFileName);
}
}
private void AddUser(UserViewModel model)
{
var user = new User
{
Email = model.Email, Password = model.Password, FirstName = model.FirstName, LastName = model.LastName, Gender = model.Gender, Birthday = model.Birthday, ProfileImage = model.ProfileImage, AboutUser = model.AboutUser
};
db.Users.Add(user);
db.SaveChanges();
}
For further reading:
http://www.mikesdotnetting.com/article/188/view-model-design-and-use-in-razor-views
http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp-net-mvc-applications/

MVC4 Registering a user with extra details

I am a beginer in MVC.
What i want is that, a user wil have a Location.
I want to keep all locations in a seprate table.
The models i came up with are:
Location Model:
public class Location
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int LocationId { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
userprofile Model:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public virtual Location location { get; set; }
}
Register Model:
public class RegisterModel
{
//Attributes for UserName , password and ConfirmPassword
public string Name { get; set; }
public virtual Location Location { get; set; }
}
Register Controller :
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new { Location = new Location () , Name = model.Name });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Now when i try to register,
Error : No mapping exists from object type HireCar2.Models.Location to a known managed provider native type.
I have been trying on this Since noon.
Can i know what is wrong in the above code.

MVC 5 Razor code-first EF Junction Table with IdentityUser

So I've got these 2 class and User coming from individual user accounts
public class User : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
public virtual ICollection<Basket> Baskets { get; set; }
}
public class Basket
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int BasketId { get; set; }
public string Name { get; set; }
public int Words { get; set; }
public virtual ICollection<User> Users { get; set; }
}
EF has created UserBaskets with 2 FK. I have items in my Basket class that I seeded.
My question is, how can I add row to my junction table in the controller? For example, a logged user click on a basket and return the Id...Now I've got
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Basket(int? basketid)
{
if (ModelState.IsValid)
{
var job = User.Identity.GetUserId();
job.Baskets.Add(basketid);
db.Users.Add(job);
db.SaveChanges();
return RedirectToAction("Basket");
}
return View(db.Baskets.ToList());
}
Thank you for any help.
I finally chose to add a junction table manually
public class UserBasket
{
[Key]
public int UserBasketId { get; set; }
public virtual User User { get; set; }
public virtual Basket Basket { get; set; }
public DateTime Date { get; set; }
}
and could add a row using identityUser like this
UserManager<User> userManager = new UserManager<User>(new UserStore<User>(db));
var user = userManager.FindById(User.Identity.GetUserId());
Basket basket = db.Basket.Find(id);
var userbasket = new UserBasket {User = user, Basket = basket, Date = DateTime.Now };
db.UserBasket.Add(userbasket);
db.SaveChanges();

MVC Automapper update

i tried to update my database table some fields
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MemberTasks membertaskdetails)
{
if (ModelState.IsValid)
{
MemberTasks Mtasks = db.MemberTask.Find(membertaskdetails.id);
Mtasks.Taskid = membertaskdetails.Taskid;
Mtasks.status = membertaskdetails.status;
AutoMapper.Mapper.Map(membertaskdetails,Mtasks);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(membertaskdetails);
}
ViewModel
public class MemberTasks
{
[Key]
[Display(Name = "ID")]
public int id { get; set; }
[Display(Name = "Task ID")]
public int Taskid { get; set; }
[Display(Name = "Status")]
public int status { get; set; }
[Display(Name = "Created By")]
public string createdby { get; set; }
[Display(Name = "Team Lead")]
public string TeamLead { get; set; }
[Display(Name = "Note")]
public string Note { get; set; }
[Display(Name = "Members")]
public string Membersid { get; set; }
}
Code is executed successfully but the problem is remaining fields also updated with null value i have 6 columns i want to update 2 columns only.
Any help ?
Your source and destination object used in AutoMapper are of the same type (MemberTasks). That's not how AutoMapper is supposed to be used. AutoMapper is used to map between domain models and view models.
So you must have a view model containing the properties passed from the view:
public class MemberTasksViewModel
{
public int Id { get; set; }
public int Taskid { get; set; }
public int Status { get; set; }
}
and then:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MemberTasksViewModel viewModel)
{
if (ModelState.IsValid)
{
MemberTasks domainModel = db.MemberTask.Find(viewModel.Id);
Mapper.Map(viewModel, domainModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}

many to many relation in asp.net mvc EF code first

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

Resources