how to add a foreign key referance in AspNetUsers in mvc5 - c#

Please can anyone help me!
I have a Model class named: Student.
Now i need to save a user with "StudentID". "StudentID" will be saved in user table as foreign key.
here is my Student class
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public int? DepID { get; set; }
public DateTime EnrollmentDate { get; set; }
[ForeignKey("DepID")]
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
and my identity model is
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Department> Departments { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
so how can i add "studentID" into user table as foreign key.

In case you just want to use the StudenID as a foreign key in a different table, you can do it like this e.g
public class Employee
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public virtual EmployeeDetail EmployeeDetail { get; set; }
}
public class EmployeeDetail
{
[Key]
[ForeignKey("Employee")]
public int EmployeeID { get; set; }
public string Adress { get; set; }
public virtual Employee Employee { get; set; }
}
In case you are talking about the actual User table created by Asp.Net Identity, then you can simply extend and customize the User table:
http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx

Related

Which one is the correct one-to-many relation in EF

i am designing a system and one of my entity has one to many relation as shown below.
public class Product
{
public int Id { get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
public Product Product { get; set; }
}
competitorProduct indicates that product has a equivalent which is sold by different store. should i define one-to-many relation as shown above or below? which one is correct?
public class Product
{
public int Id { get; set; }
public virtual ICollection<CompetitorProduct> CompetitorProducts{ get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
}
Assuming it is a one to many relationship (what would happen if a competitor product was competing with more than one of your products for example) you can do both and add in a foreign key as well.
public class Product
{
public int Id { get; set; }
public virtual ICollection<CompetitorProduct> CompetitorProducts { get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
You can then set up your relationship using fluent API as so:
modelBuilder.Entity<CompetitorProduct>(entity =>
{
entity.HasOne(e => e.Product)
.WithMany(e => e.CompetitorProducts)
.HasForeignKey(e => e.ProductId)
.HasConstraintName("FK_ComptetitorProduct_Product");
});
This way you can access the competitor products from the product and the product from the competitor products.
Here is a quick example of a ecommerce site I have worked on and how we did table relations.
I removed a bunch of the fields so you can see what you really need. Once to make relations and run Add-Migration EF will handle the FK constraints for you as long as you identified them in models like how I have below.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
Active = true;
CreateDateTimeUtc = DateTime.UtcNow;
ModifiedDateTimeUtc = DateTime.UtcNow;
}
[StringLength(500)]
public string FirstName { get; set; }
[StringLength(500)]
public string LastName { get; set; }
[StringLength(1000)]
public string Address { get; set; }
[StringLength(100)]
public string Unit { get; set; }
[StringLength(250)]
public string City { get; set; }
[StringLength(25)]
public string State { get; set; }
[StringLength(20)]
public string ZipCode { get; set; }
//This will give access to a list of child carts a user could have
[Index]
public bool Active { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
// Account Profile Image
public byte[] ProfileImage { get; set; }
[StringLength(500)]
public string ProfileFilename { get; set; }
[StringLength(100)]
public string ProfileMimeType { get; set; }
}
[Table("Cart", Schema = "dbo")]
public class Cart : AbstractTable
{
public Cart()
{
IsComplete = false;
}
//This create relation to user table where I can get one unique user.
[StringLength(128)]
[ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
//These link us to child tables of Cart where we can get a LIST of the items below
public virtual ICollection<CartCategory> CartCategories { get; set; }
public virtual ICollection<CartItem> CartItems { get; set; }
// Marked when a payment/receipt is generated based off of this cart
public bool IsComplete { get; set; }
}
[Table("CartItem", Schema = "dbo")]
public class CartItem : AbstractTable
{
//This will return one unique cart id and let us access it as the parent record
[ForeignKey("Cart")]
public Guid CartId { get; set; }
public virtual Cart Cart { get; set; }
// Signifies if this was paid for in a receipt
public bool IsComplete { get; set; }
public virtual ICollection<CartItemCustomField> CustomFields { get; set; }
}

Show data from database table

I am trying to get my data from database to display on my view. Currently on my database table there are these columns: ID, ReportDescription, DateReported, CustomerId and MovieId.
What I need to do is use the CustomerId and MovieId to get to the name of the Customer and the name of the Movie.
This is my Model:
public class Malfunction
{
public int Id { get; set; }
[Required]
public Movie Movie { get; set; }
[Required]
public Customer Customer { get; set; }
[Required]
[StringLength(255)]
public string ReportDescription { get; set; }
public DateTime DateReported { get; set; }
}
This is the Controller:
private ApplicationDbContext _context;
public TablesController()
{
_context = new ApplicationDbContext();
}
// GET: Tables
public ActionResult MalfunctionsList(MalfunctionDTO malfunctionDTO)
{
var malfunctions = _context.Malfunctions.ToList();
return View(malfunctions);
}
}
And this is the DTO:
public class MalfunctionDTO
{
public int CustomerId { get; set; }
public List<int> MovieIds { get; set; }
public Customer Customer { get; set; }
public Movie Movie { get; set; }
public string ReportDescription { get; set; }
}
IdentityModel:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<MembershipType> MembershipTypes { get; set; }
public DbSet<Movie> Movies { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Rent> Rents { get; set; }
public DbSet<Malfunction> Malfunctions { get; set; }
Am i supposed to add properties like CustomerId and MovieId in my model in order for it to work?
Worth noting that i am very new to MVC and EF, so forgive me if I am a bit confused.
Your need to change your mapping to look like below.
// For Id
Mapper.CreateMap<Malfunction, MalfunctionDTO>()
.ForMember(dest => dest.CustomerId,
opt => opt.MapFrom(src => src.Id));
Update
I assume you are not using Entity Framework Core.
Update your context like below. vrtual key word added.
public virtual DbSet<Movie> Movies { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
Also change
public class Malfunction
{
public int Id { get; set; }
[Required]
public virtual Movie Movie { get; set; }
[Required]
public virtual Customer Customer { get; set; }
[Required]
[StringLength(255)]
public string ReportDescription { get; set; }
public DateTime DateReported { get; set; }
}
Then you may need to add configuration in your OnModelCreatingmethod something like this.Try without this first, if not work then add below configurations.
modelBuilder.Entity()
.WithRequired(m => m.Movie);
modelBuilder.Entity()
.WithRequired(m => m.Customer);

Many to Many Relationship with extra columns in EF 6 Code?

Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.
How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?
Do I just make in code another class and then hook it up somehow?
DB Context
public class MyContext : DbContext
{
public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
{
// this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
[Key]
public Guid StudentCourseId { get; set; }
public Guid StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; } // Include this so you can access it later
public Guid CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
public int Permissions { get; set; }
}
public class Course
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; } = new >();
}
public class Student
{
[Key]
public Guid Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Course> Courses { get; set; } = new List<Course>();
}
Given you are code first I would do something like the following.
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Students { get; set; }
}
public class StudentCourse
{
[Key]
public int StudentCourseId { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public Student Student { get; set; } // Include this so you can access it later
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
}
EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships. The properties will look the same, but without the [ForeignKey("")]

how to inherit the values of a foreign key in MVC 5? Invalid column name 'student_student_name'

I kept getting this error
Invalid column name 'student_student_name'
Here is my class for my database context
public class CSdbConnectionString : DbContext
{
public CSdbConnectionString()
: base("CSdbConnectionString")
{ }
public DbSet<appointment> appointments { get; set; }
public DbSet<faculty> faculties { get; set; }
public DbSet<sched> scheds { get; set; }
public DbSet<student> students { get; set; }
}
My appointment class needs to inherit the values of the foreign key faculty and student
[Table("appointment")]
public class appointment
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int appointment_id { get; set; }
public string appointment_description { get; set; }
public int student_id { get; set; }
public int faculty_id { get; set; }
public virtual student student { get; set; }
public virtual faculty faculty { get; set; }
}
Here is my faculty class
[Table("faculty")]
public class faculty
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int faculty_id { get; set; }
public string faculty_name { get; set; }
public string faculty_lname { get; set; }
public string faculty_email { get; set; }
public string faculty_password { get; set; }
public string faculty_dept { get; set; }
}
Here is my student class
[Table("student")]
public class student
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public string student_name { get; set; }
public string student_lname { get; set; }
public string student_email { get; set; }
public string student_password { get; set; }
public string student_number { get; set; }
public string student_program { get; set; }
}
The faculty class is working fine. I can inherit the values in my view
#item.faculty.faculty_name
I also used public virtual faculty faculty { get; set; } in another class to inherit the faculty values and it worked fine. I did the same thing to inherit the values in student class and it kept saying invalid column name.
I've already searched many solution here in stackoverflow and what happen is it just keeps getting new errors.
I tried adding this to the parent class which will be the one inherited
public virtual ICollection<appointment> appointments { get; set; }
and added this code
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<appointment>()
.HasRequired(c => c.student)
.WithMany(p => p.appointments)
.HasForeignKey(c => c.student_id);
}
and still there are errors.
All I did for the faculty to be inherited was add this to the child class public virtual faculty faculty { get; set; } and now I am trying to do the same with student and I always have errors. Can someone help me?
Well, first thing: Your student class has a string as a PrimaryKey and your are mapping it to an int in your appointment class
public int student_id { get; set; }
try to change it and see if it works.

One-to-Many Relationship with ApplicationUser class

I have this User class :
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
And this Project Class :
public class Project
{
public int ProjectID { get; set; }
public int UserID { get; set; }
public string ProjectTitle { get; set; }
public virtual User User { get; set; }
}
There is a one-to-many relationship between User and Project as you can see.
Instead of my User class, I want to use Identity's ApplicationUser class. So would it be ok if I change IdentityModels.cs to this :
public class ApplicationUser : IdentityUser
{
public int UserID { get; set; }
public string ProjectTitle { get; set; }
public virtual User User { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
And How should I change AccountViewModel.cs? should I add these
public string Email { get; set; }
public int UserID { get; set; }
to every ViewModel in that file?
Finally how should I change Project class? Should I do this :
public class Project
{
public int ProjectID { get; set; }
public int UserID { get; set; }
public string ProjectTitle { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
If you can answer to my this long question, I would be very glad. Thanks.

Categories