ORM Code first - fix during design - c#

I run into a little trouble understanding object relational mapping in MVC4 simple web application in which there are users and their posted comments.
One user must have a lot of comments. So I added in my UsersContext class public DbSet<UserWork> UserComments { get; set; }
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UserWork> UserComments { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? UserComId { get; set; }
[ForeignKey("UserComId")]
public virtual UserComment UserComLog { get; set; }
}
public class UserComment
{
[Key]
public int UserComId{ get; set; }
public int UserId { get; set; }
public string Comments{ get; set; }
public DateTime postDate{get;set}
}
I am now stuck at realizing how all comments posted daily are stored such that I later can make a query like e.g SELECT * FROM UserComment Inner join UserProfile ON UserComment.UserId=UserProfile.UserId WHERE postDate BETWEEN (...) AND (...)

I'm assuming you're using Code First Migrations.
Seems like you need to edit your UserProfile class a little bit to allow for a user to have multiple comments. You need to make UserComLog a collection. Like:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<UserComment> UserComLog { get; set; }
}
With that, you'll have a user with multiple comments. Then, with the UsersContext you can access the database tables that Entity Framework have created for you. You just need to use your data context to write a Linq statement to access the data.
var context = new UsersContext();
var comments = context.UserComments.Where(d => d.postDate > new DateTime(2013,3,12) && d.postDate < new DateTime(2013,2,12) && d.UserId == userId);
comments would be a IQueryable<UserComment> which you can then pass into a loop to display on a page, or filter further if you wish.

Related

Entity Framework Core no connected objects

I created local database using EF core and code-first method.
The db imitates library, so I have 3 simple tables: users, books and reservations.
Issue occurs when I want to get nested data like find one book and get its reservation.
I think I should be able to use
List<Reservation> reservations = book.Reservations;
but I have to use
List<Reservation> reservations = libraryContext.Reservations.
Where(r=> r.Book == book).ToList();
But the main reason I need help is this fragment
BookReservationsModel bookReservationsModel = new BookReservationsModel
{
BookTitle = book.Title,
Reservations = reservations
};
// I want to display emails in View.
for (int i = 0; i < bookReservationsModel.Reservations.Count; i++)
{
Debug.WriteLine(bookReservationsModel.Reservations[i].User.Email);
}
I cannot get access to users because they are nulls. In database everything is stored as it should be (correct ids). Of course I could copypaste certain emails to new created list but it's inefficient and I know I should be able to use it that way. I worked before with EF for Framework and I tried google the problem but couldn't find the solution.
Models and context code.
public class User
{
[Key]
public int UserID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Salt { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
public class Book
{
[Key]
public int BookID { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Author { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime PublishDate { get; set; }
[Required]
public string Description { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
public class Reservation
{
[Key]
public int ReservationID { get; set; }
[Required]
public DateTime ReservationDate { get; set; }
[Required]
public int UserID { get; set; }
[ForeignKey("UserID")]
public User User { get; set; }
[Required]
public int BookID { get; set; }
[ForeignKey("BookID")]
public Book Book { get; set; }
}
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions options) : base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Reservation> Reservations { get; set; }
}
Attempting to use a navigation property on the book entity without doing either of the following will result in the property being null.
Including the property before materializing the entity with .First()/.Single()
https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager
Configuring EFCore to AutoInclude navigation properties by default.
https://dotnetcoretutorials.com/2021/03/07/eager-load-navigation-properties-by-default-in-ef-core/
I suggest when querying for the book to use the Include and ThenInclude methods so the Reservations and Users are populated.
var book = await libraryContext.Books
.Include(x => x.Reservations)
.ThenInclude(x => x.User)
.SingleAsync(x => x.BookID == myBookId);

How to design one to many relationship in efcore?

Hi I am working on entity framework core. I have user table and user may be part of multiple projects. And user for each project has to enter time sheet data. For example below is my user table.
public class User
{
[Key]
public string Id { get; set; }
public string name { get; set; }
public string emailId { get; set; }
}
Below is my project table.
public class Project
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public string userId { get; set; }
}
Here User may belong to multiple projects. Now for each project user has to enter timesheet data. Below is timesheet table.
public class TimeSheetData
{
[Key]
public string id { get; set; }
public string project_id { get; set; }
public string hours_logged { get; set; }
}
I have to define this in entity framework core. One user may be part of multiple projects and user needs to enter data to timesheet for each project. How can I define relationship with respect to above table?
In user table Do I need to add something like Public List<Project> Projects? Also In Project table Public List<Timesheet> Timesheets something I have to define here. Can some one help me to understand this? Any help would be greatly appreciated. Thanks
Assuming you will be changing string to int ids, does something below work?
public class User
{
public User()
{
this.Projects = new HashSet<Project>();
}
[Key]
public int Id { get; set; }
public string name { get; set; }
public string emailId { get; set; }
public virtual ICollection<Project> Projects { get; set;}
}
public class Project
{
public Project()
{
this.TimeSheetData = new HashSet<TimeSheetData>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int userId { get; set; }
[ForeignKey("userId")]
public virtual User User {get; set; }
public virtual ICollection<TimeSheetData> TimeSheetData { get; set;}
}
public class TimeSheetData
{
[Key]
public int id { get; set; }
public int project_id { get; set; }
[ForeignKey("project_id")]
public virtual Project Project {get; set; }
public string hours_logged { get; set; }
}

Entity Framework Conditional join

I have created an MVC using Entity framework and I've encountered a situation which I don't know how to resolve.
I'm using the EF auto joins and relations (all my table models were created automatically by EF) .
Now for the problem - I have a table of customers, which has two(relavent) fields - personID and employerID . Only one of them contains data , the other will be null (a customer is either a person , or an employer) . When I try to include employer model in the result set, I'm getting thrown (without any message , when I debug I see that the content has data but the employeer is sometimes NULL) I'm also not sure about how the design should look like. This is my code :
Customer:
public partial class Customer
{
public Customer()
{
Account = new HashSet<Account>();
}
public long Id { get; set; }
public int? PersonId { get; set; }
public int Type { get; set; }
public int? EmployerId { get; set; }
public Employer Employer { get; set; }
public ICollection<Account> Account { get; set; }
}
Employer:
public partial class Employer
{
public Employer()
{
Customer = new HashSet<Customer>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? IdType { get; set; }
public ICollection<Customer> Customer { get; set; }
}
Person:
public partial class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Sex { get; set; }
public DateTime? BirthDate { get; set; }
public int IdType { get; set; }
}
Now when I'm running in my repository:
var collectionBeforePaging = _context.Customer
Everything works, but Employer is NULL. If I use :
var collectionBeforePaging = _context.Customer.Include(a => a.Employer)
Then the project fails .
How can I make this joins?
Please define ForeignKey for Customer
public int? EmployerId { get; set; }
[ForeignKey(nameof(EmployerId))]
public virtual Employer Employer { get; set; }
What version of EF you use? I think you missing something like that :
In Employer :
[ForeignKey("EmployerId")]
[InverseProperty("Customers")]
public virtual Employer Employer { get; set; }
public int? EmployerId { get; set; }
In Customer :
[InverseProperty("Employer")]
public virtual ICollection<Customer> Customers { get; set; }
It can also be done in the Dbontext object

Many to Many relationship with ApplicationUser

I am building a Code-First, Many-To-Many relationship between my ApplicationUser class and a Lesson class. When the model is created, Entity Framework builds the two tables and the intersecting pivot table. However, neither table seems to take in data from the pivot table (LessonApplicationUsers). Both List variables do not seem to hold either the list of Students or the list of Lessons. Both entities i'm trying to marry up already exist in the database
ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string Address { get; set; }
public int? Age { get; set; }
public ClassLevel? ClassLevel { get; set; }
public string FirstName { get; set; }
public int? Height { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
public string Postcode { get; set; }
public string Town { get; set; }
public int? Weight { get; set; }
public ApplicationUser()
{
Lessons = new List<Lesson>();
}
public ICollection<Lesson> Lessons { get; set; }
}
Lesson Class
public class Lesson
{
[Key]
public int LessonID { get; set; }
public LessonType ClassType { get; set; }
public ClassLevel? ClassLevel { get; set; }
public DateTime ClassStartDate { get; set; }
public DateTime ClassEndDate { get; set; }
public float ClassCost { get; set; }
public int? InstructorID { get; set; }
public Lesson()
{
Students = new List<ApplicationUser>();
}
public ICollection<ApplicationUser> Students { get; set; }
public enum LessonType {Group,Private}
}
My DBContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Lesson> Lessons { get; set; }
public DbSet<ApplyViewModel> Applications { get; set; }
And finally, the code i'm using to add in the pivot table data. This is activated when the user presses a button on the booking form.
public ActionResult BookUser()
{
//Gather required variables
ApplicationUser user = db.Users.First(i => i.UserName == User.Identity.Name);
int classID = int.Parse(Request.Form["classID"]);
using (db)
{
var editedLesson = db.Lessons.Single(s => s.LessonID == classID);
db.Lessons.Attach(editedLesson);
var editedUser = db.Users.Single(s => s.Id == user.Id);
db.Users.Attach(editedUser);
editedLesson.Students.Add(editedUser);
db.SaveChanges();
}
return View("Index");
When I try and run it, when i press my book button, it runs through the code and executes. checking the database it has indeed inserted the key values into the pivot table. When i load the model of the lesson to view its details, the Student attribute has a count of 0. I've been at this for days and i've got the feeling i'm missing something kickself simple....but i've gone over it a dozen times and can't see what i'm doing wrong...
Mark your lists with virtual to enable lazy loading. Also is not required to initialize the lists Lessons = new List<Lesson>();

EF code Model for e-tender system in MVC4

Am building tender board Application am getting some confusing in how structure my model using >> entity-framework in >> MVC4
Here the descriptions:
In my simple membership Role Table , I have:
(Admin,Tender,Provider,Member)
Administration: he have right to change normal user role from “Member” to “Provider and prove winner bidder after tender organization approved.
Suppliers: Normal users will be assigning as “member” and will be activated by Administration to be provider and then they can bid any projects they want.
Projects: created by Tender Organization Users every project has many requirements
Requirement: each one related to project.
Tenders: Here my problem actually Tender are “Ministries in country and have to be set in system” but each ministry obvious have many users “Manager, let say 5 in each” who will vote for supplier.Mangers can vote to only those suppliers which are laid under the same ministry.
Do I miss others tables?
Also I don’t really know how to structure all the tables with relations and also with (UserprofileTbale, and Role Table):
Here my try, help me on that.
My DBContext:
public class ProjectContext : DbContext
{
public ProjectContext()
: base("OTMSProjects")
{
}
public DbSet<ProjectEntry> Entries { get; set; }
public DbSet<Requiernments> RequiernmentEntries { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Tender> Tenders { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
//public DbSet<UserRoles> UserRoles { get; set; } // do I have to set this too?
}}
My tables:
public class ProjectEntry
{
[Key]
public int ID { get; set; }
[Required]
public string ProjectName { get; set; }
public string Description { get; set; }
public string Statue {get; set; }
public string UplodedFiles { get; set; }
public string Budget { get; set; }
public string EstimateTime { get; set; }
public string Criterias { get; set; }
public DateTime? DueDate { get; set; }
// Relations with others tables
public virtual Tender Tender { get; set; }// every project have only one tender
public virtual ICollection<Supplier> Suppliers { get; set; } // every project have one or more supplier
public virtual ICollection<Requiernments> Requirements { get; set; }
}
........
public class Requiernments
{
[Key]
public int RequiernmentId { get; set; }
public int ID { get; set; }
public string RequiernmentName { get; set; }
public string RequiernmentType { get; set; }
public string RequiernmentPrioritet { get; set; }
public float RequiernmenWhight { get; set; }
public string ProviderAnswer { get; set; }
public string ProviderComments{ get; set; }
public virtual ProjectEntry Projects { get; set; }
}
........
public class Supplier
{
[Key]
public int SupplierId { get; set; }
public int ID { get; set; }
public int SupplierName { get; set; }
public int SupplierCat { get; set; }
public virtual ICollection<ProjectEntry> Projects { get; set; }
}
......
public class Tender
{
[Key]
public int TenderId { get; set; }
public string TenderName { get; set; }
public string TenderMinstry{ get; set; }
public int ID { get; set; }//link to project
public int UserId { get; set; } //this links to the userid in the UserProfiles table
public virtual ICollection<ProjectEntry> Projects { get; set; }
//public virtual ICollection<UserProfile> Userprofile { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
My membership table in my AccountModel created by defualt in Mvc4 ( I only add the RoleTable :
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public ICollection<UserRoles> UserRoles { get; set; }
}
[Table("webpages_Roles")]
public class UserRoles
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
[ForeignKey("UserId")]
public ICollection<UserProfile> UserProfiles { get; set; }
}
Am not sure also about how to link the Userprofile with Tender Table and supplier Table?
Not sure what you are missed or not. but as per database creation you must follow your business logic and normalization rules.
Some of my suggestions are here:
1. ProjectEntry
here you should create a Status Table separately and gives its reference key as StatusID into the ProjectEntry table.
Requirement
you should create Requirement Priority and Type tables are separately.
Add separate table for provider question and answers. I hope you need to store more than one question answers for single requirement.
Supplier
Add Separate Table for Supplier category
Tender
Create Tender Ministry table separately and give its reference to the tender table.
you should make a table for Uploaded files as Documents. It should contains ID, ProjectId, Documentname, DocumentType, DocumentShortDescription, uplodatedDateTime fields.

Categories