I am relatively new to MVC and I am working on making a webshop in MVC.
My current model for displaying products (or shopping cart items):
public class ShoppingCartItems
{
public virtual int ID { get; set; }
[Required]
public virtual string ProductName { get; set; }
public virtual int CategoryID { get; set; }
public virtual DateTime DateAdded { get; set; }
[Required]
[DataType(DataType.Currency)]
public virtual decimal ProductPrice { get; set; }
public virtual int AmountAvailable { get; set; }
}
Should I add a property here in order to make a connection between a user who has logged in and the products the user chose to add to the shoppingcart or should I take a look at this matter in the controller instead (or make use of both controller and model to relate the two)?
In this example I also make use of a CategoryID which should point to a category class containing the (available) option values of categories. How do I make such a relationship in MVC between classes?
To identify user who is logged you could use Membership, Simple Membership, Identity or implement your own authetication. You can read more for example here. http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity. For category problem you can just add property of type Category to your model. Details depend on what ORM you are using.
Related
Using ASP.NET Core Identity with Entity framework Core i need to add different types of users in my app:
Let's say that i need two types of users: "Student" and "Teacher"; both of them are also ApplicationUsers since they have to be authenticated to access the app.
I have accomplish that creating two tables: one for Student and one for Teacher. Both tables are one-to-one related with the ApplicationUser table.
I'd like to know if this is correct or if i'm doing something wrong, because when updating the database with migrations it throws the error "FOREIGN KEY 'FK_Student_AspNetUsers_Id' in 'Student' table may cause cycles or multiple cascade paths. specify ON DELETE NO ACTION or UPDATE NO ACTION". And, in any case, if it goes right, at the end i'd have an ApplicationUser class with two columns (one for StudentId and another for TeacherId), and one of them will always be null since an ApplicationUser can be a Student or a Teacher, but not both.
Here is my code so far:
public class ApplicationUser : IdentityUser<int>
{
public string Name { get; set; }
[ForeignKey("Teacher")]
public int? TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
[ForeignKey("Student")]
public int? StudentId { get; set; }
public virtual Student Student { get; set; }
}
public class Student
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string MotherMaidenName { get; set; }
public DateTime BirthDate { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ApplicationUser User { get; set; }
}
public class Teacher
{
[Key,ForeignKey("User")]
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string MotherMaidenNAme { get; set; }
public virtual ApplicationUser User { get; set; }
}
UPDATED: I've set TeacherId and StudentId as nullable, so the Error mentioned above is gone.
You shouldn't create different tables for each user type you have.
You should create roles and assign that roles to a user. For example create a role student and a role teacher and assign them acording to your needs.
So I would say what you've done isn't a good design.
When you need to save additional values for a student/teacher than I would do something similar to your design.
But I wouldn't add ID's for my student/teacher to my ApplicationUser class.
I would simply add a UserId to my student/teacher class.
So the design issue should be that you're trying to put that stuff into the ApplicationUser class.
I am new to ASP.NET MVC. Using Entity Framework 6, I am working on a project to store employee skills in a database. The user can enter a new skill into a list of skills. I would like to keep track of who added the new skill. I have a table of all of the employees.
These are the models for the two tables.
public partial class Skill
{
public int ID { get; set; }
public string Skill { get; set; }
[ScaffoldColumn(false)]
public int LastActionUserID { get; set; }
public virtual Employee Employees { get; set; }
}
public partial class Employee
{
public int ID { get; set; }
public string EmployeeLAN { get; set; }
public int LastActionUserID { get; set; }
public virtual Employee Employees { get; set; }//References itself for LastActionUserID
public virtual ICollection<Skill> Skills{ get; set; } //Omitted in initial question
}
There is a 1 to Many mapping of Employee to Skill. I can get the current user's EmployeeLAN but how do I get the id of that Employee record to put into the Skill table automatically when then new skill is created? Must I convert the table to an enumerable object and use SingleOrDefault or LINQ? Or is there an easier way using EF6? Also, setting this automatically when a new skill is created would be done in the controller, correct?
You're on the right track and you should continue to use EF6.
The Employee class should have a Skills list. That way you can call myEmployee.Skills and have a list of all the skills available.
public partial class Employee
{
public int ID { get; set; }
public string EmployeeLAN { get; set; }
public int LastActionUserID { get; set; }
public virtual ICollection<Skill> Skills{ get; set; }
}
Also, setting this automatically when a new skill is created would be done in the controller, correct?
You'll need to add to the Skills list, call AddOrUpdate() to mark this as changed, then SaveChanges() to persist it to the database.
I recommend learning more from the MSDN docs and Julie Learman's
Entity Framework videos on Pluralsight
Well it's a noob question but i can't figure out the solution.
I have two entities, user and team. User can create a team and invite other users. User can belong only one team but team has multiple users.
What would be the most correct relationship between users and team? I also need DateJoin in team and other properties. Should i create third table(TeamMembers)?
Here is code what i tried :
public class TeamMember
{
public int Id { get; set; }
[ForeignKey("Team")]
public int TeamId { get; set; }
public Team Team { get; set; }
[ForeignKey("User")]
public string UserId { get; set; }
public User User { get; set; }
public DateTime DateJoin { get; set; }
public RoleEnum MemberRole { get; set; }
}
public enum RoleEnum
{
Capitan = 1,
Main,
Sub
}
And team has list of members:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public ICollection <TeamMember> Members { get; set; }
}
But third table means many to many relationship...
If the user can only belong to one team then this is the correct format.
However, if you think you might change this policy in the future then I do suggest you use a many to many relationship. This would also allow you to keep track of the previous teams your users belonged to, by simply using a "DateLeave" property for example.
As my domain classes I have Person and FavoritePerson classes as follows.
public class CompanyPerson : ICompanyPerson
{
[Key]
public Guid PersonId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public class CompanyFavoritePerson : IFavoritePerson
{
[Key]
public Guid FavoritePersonId { get; set; }
[Column(TypeName = "datetime2")]
public DateTime CreateDate { get; set; }
public Guid? CompanyPerson_PersonId { get; set; }
[StringLength(128)]
public string CompanyUser_UserId { get; set; }
public virtual CompanyPerson CompanyPerson { get; set; }
public virtual CompanyUser CompanyUser { get; set; }
}
In my web application I will need to show List of Favorite Person. So my view model is like this;
public class FavoritePersonViewModel
{
public Guid FavoritePersonId { get; set; }
public DateTime CreateDate { get; set; }
public Guid? CompanyPerson_PersonId { get; set; }
public string CompanyUser_UserId { get; set; }
//Option1: PersonViewModel PersonViewModel {get; set; }
//Option2: public string Title {get;set;}
}
Since I need to show Title of the favorite user in the list (where title belongs to Person class) which way will match with best practices?
Referencing a viewModel from another viewModel or extend viewModel with required extra attributes and fill them in business layer?
After some more research on this topic; I found out at this question
What is ViewModel in MVC?
it is clearly stated that:
View models can combine values from different database entities.
As like below;
So now you have data from the Employees and Departments tables in one
view model. You will just then need to add the following two
properties to your view model and populate it with data:
public int DepartmentId { get; set; }
public IEnumerable<Department> Departments { get; set; }
So I am going with Option 2.
The ViewModel pattern is just one of many patterns that fall into the 'Separated Presentation Pattern' bucket.
It's very important that you think about the requirements of your view before designing the ViewModel. For instance, if you have two widgets in your view and every widget has its own ViewModel, composite ViewModel is suitable in the situation, but if the view is just one that uses multiple domain classes, whether you have View model for each one, composite ViewModel is not suitable because it increases the complexity and every change in one ViewModel can break your code.
Thus, based upon your question
As my domain classes I have Person and FavoritePerson classes.
Since I need to show Title of the favorite user in the list (where title belongs to Person class).
It seems to me that composite ViewModel is not a good choice and you should design a new ViewModel.
It is also worth to read the ViewModel Best Practices
I am working with c # and nhibernate in mysql, I have a list that stores sell products which at some point may be the same but different price.
Product A - Price 3.00
Product A - Price Two: 2.50
when wanting to save it shows me the following, which I'm sure is that nhibernate can not do that, if I am wrong please help me I need to solve this problem, thanks.
a different object with the same identifier value was already associated with the session: 72, of entity: DAL.Ent.Sale
also mention that my database if that income allows the same product at a different price because it has a unique identifier that makes them different.
Going from the information that you have provided, I would say that you need to look at the way your Domain objects are modeled.
You need to separate the product and the price of that product for a given store. There needs to be a joining table in the middle to hold the relationship between a store, the product and the price of the product. So that there is only one price for a product for a given store per record.
So you end up with something like this.
public class Product
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual ISet<Price> Prices { get; set; }
}
public class Price
{
public virtual Guid Id { get; set; }
public virtual Product Product { get; set; }
public virtual Store Store { get; set; }
public virtual decimal Price { get; set; }
}
public class Store
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual ISet<Price> ProductPrices { get; set; }
}