I have a linq statement that combines Residents and Requests table like so
var resident = await _context.Resident
.Include(s => s.Requests)
.FirstOrDefaultAsync(m => m.ID == id);
The problem is that all requests show up even those that are not related to the Resident.
I have tried adding a Where statement but still getting all requests.
var resident = await _context.Resident
.Include(s => s.Requests)
.Where(s =>s.UserID == "f7c6ceef-663f-48af-9a84-b0a3d2a97601")
.FirstOrDefaultAsync(m => m.ID == id);
For reference this is the Resident Model Class
public class Resident
{
public Resident()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public string UserID { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[Required]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "Number of Cameras")]
public int CameraQty { get; set; }
public DateTime CreatedAt { get; set; }
public string Latlng { get; set; }
public ICollection<Camera> Cameras { get; set; }
public ICollection<Request> Requests { get; set; }
}
This is the Request Model Class
using System.ComponentModel.DataAnnotations;
namespace MVC_NeighbourhoodCamera.Models
{
public class Request
{
public Request()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public int ResidentID { get; set; }
public string UserID { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
[DataType(DataType.MultilineText)]
public string Details { get; set; }
public Boolean Completed { get; set; }
public Boolean Active { get; set; }
public DateTime CreatedAt { get; set; }
public Resident Resident { get; set; }
}
}
You do not have foreign key properly set in Resident->Requests one-to-many relationship.
Fix your Request class as following by adding ForeignKeyAttribute (+make migration and run it in to the db):
public class Request
{
//Other properties
..
public int ResidentID { get; set;}
ForeignKey["ResidentID"]
public Resident Resident { get; set;}
}
More info can be found i.e here.
Related
I have my unit of measure in the database, when you save a unit, you save the name, id, tenant Id and more to the table, then UnitSize get saved to its own table UnitOfMeasureSize. It shares the UnitOFMeasureId and I need to figure out how to get the the UnitSize back and display it with the UOM name on the interface. I read up on entities and feel like i have it right so I am not sure what I am doing wrong. Any suggestions?
here is my dropdown
namespace Mudman.Data.Entities
{
[Table("UnitOfMeasure")]
public class UnitOfMeasure : IEntityBase, IAuditBase
{
[Key]
[Column("UnitOfMeasureId")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
[Required]
[ForeignKey("TenantId")]
public string TenantId { get; set; }
[JsonIgnore]
public virtual Tenant Tenant { get; set; }
public string Name { get; set; }
public virtual IEnumerable<UnitOfMeasureSize> UnitSize { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
[StringLength(255)]
public string CreateUserId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime UpdateDate { get; set; }
[StringLength(255)]
public string UpdateUserId { get; set; }
}
}
namespace Mudman.Data.Entities
{
[Table("UnitOfMeasureSize")]
public class UnitOfMeasureSize : IEntityBase, IAuditBase
{
[Key]
[Column("UnitOfMeasureSize")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
[Required]
[ForeignKey("TenantId")]
public string TenantId { get; set; }
[JsonIgnore]
public virtual Tenant Tenant { get; set; }
[Required]
[ForeignKey("UnitOfMeasureId")]
public string UnitOfMeasureId { get; set; }
public virtual UnitOfMeasure UnitOfMeasure { get; set; }
[Required]
public int UnitSize { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
[StringLength(255)]
public string CreateUserId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public DateTime UpdateDate { get; set; }
[StringLength(255)]
public string UpdateUserId { get; set; }
}
}
public async Task<IEnumerable<UnitOfMeasureViewModel>> GetAllAsync()
{
var result = await _unitOfMeasureRepo.FindByAsync(uom => uom.TenantId == TenantId);
result.OrderBy(r => r.Name);
return _mapper.Map<List<UnitOfMeasure>, List<UnitOfMeasureViewModel>>(result.ToList());
}
Here is how I am trying to grab the Unit Sizes in my AdminStore
public getUnitSizes(unitOfMeasureId: string) {
return this.api.get(`/${unitOfMeasureId}/UnitSize`)
.then(
(data: any) => data,
(error: any) => {throw error;}
);
}
public getUnitSizes = async (unitOfMeasureId: string) => {
const list: any[] = await this.adminAPI.getUnitSizes(unitOfMeasureId);
runInAction(() => {
this.unitSizes = list;
});
}
I am developing HelpDesk application using ASP.NET.CORE 5.0 MVC and right now I want to retrive User information from ticket, like UserName,LastName,Email etc
So far I create a little guide using SQL Query
SELECT u.Id as UserId,
u.UserName as Username,
u.Email as UserEmail,
t.UserId as TicetUserId
FROM AspNetUsers u,Tickets t
WHERE u.Id = 2 and t.UserId = 2
So far I want to write this in C# using LINQ and _unitOfWork.
I will try to demostrate my Models starting from basic one which is Ticket.cs
public class Ticket
{
[Key]
public int Id { get; set; }
[Display(Name = "Opis")]
public string Description { get; set; }
[Display(Name = "Kratak Opis")]
[MaxLength(20, ErrorMessage = "Maximalan broj karaktera je 20")]
public string ShortDescription { get; set; }
[Display(Name = "Datum i vrijeme slanja")]
public string DateAndTime { get; set; } = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
//[Display(Name = "Datum i vrijeme zavrsetka")]
//public DateTime Answered { get; set; }
[Display(Name = "Vrsta tiketa")]
public int TicketTypeID { get; set; }
[ForeignKey("TicketTypeID")]
public virtual TicketType TicketType { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public virtual Client Client { get; set; }
public string Status { get; set; } = TicketStatus.Otvoren.ToString();
}
From TicketModels I have alredy ApplicationUser class and UserId which is ForeignKey to ApplicationUser
And in ApplicationUser.cs I have all property which I need to retrive
public class ApplicationUser : IdentityUser<int>
{
[Required]
[Display(Name = "Ime")]
public string Name { get; set; }
[Required]
[Display(Name = "Adresa")]
public string StreetAddress { get; set; }
[Required]
[Display(Name = "Grad")]
public string City { get; set; }
[Required]
[Display(Name = "Postanski broj")]
public string PostalCode { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
[NotMapped]
public string Role { get; set; }
//[NotMapped]
//public int RoleId { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> RoleList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> ClientList { get; set; }
}
But basically most property which I need is UserName,EmailAddress.
Is there some way to figure out something like this, since I am begginer in RepositoryPattern and UnitOfWork and it is a little bit confusing me and whatever I try to retrive data I get wroong output.
I try something like:
var userEmail = _unitOfwork.Ticket.GetAll(t => t.Id == ticketId);
This will retrive TicetId which is correct. But how to get TicetId base on UserId ?
I'm trying to update a many-to-many relationship. I have two models, diary and tags. The model diary contains a list of tags and tags contains a list of diaries. But whenever I try to add another tag to an existing list or change an existing one I get thrown an exception:
The entity type List`1 is not part of the model for the current context.
Does my way of updating even work on collections? Or is there another approach I should be looking at?
Diary Model
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
Entry Model
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
Tag Model
public class Tag
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Diary> Diaries { get; set; }
}
Update Method
public void UpdateDiary(Diary updatedDiary)
{
var searchResult = SearchDiary(updatedDiary);
if (searchResult != null)
{
updatedDiary.IdDiary = searchResult.IdDiary;
_context.Entry(searchResult).CurrentValues.SetValues(updatedDiary);
_context.Entry(searchResult.Tags).CurrentValues.SetValues(updatedDiary.Tags);
_context.SaveChanges();
}
}
SearchDiary Method
public Diary SearchDiary(Diary searchDiary)
{
var queryResult =
_context.Diaries.Include(d => d.Entries).Include(d => d.Tags)
.Where(d => (d.NameDiary == searchDiary.NameDiary && d.CreationDate == searchDiary.CreationDate) || d.IdDiary == searchDiary.IdDiary);
return queryResult.FirstOrDefault();
}
Thank you for reading
Here is one way:
DiaryModel
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
EntryModel
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public virtual Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
For Search
public Diary SearchDiary(int DiaryId)
{
return _context.Diaries
.Include(p => p.Entries)
.Include(p => p.Tags)
.FirstOrDefault(p => p.IdDiary == DiaryId);
}
For Update
public void UpdateDiary(Diary Diary)
{
_context.Update(Diary);
_context.SaveChanges();
}
You should pass the modified Diary object to the update functions.
My database has a variety of different tables that reference each other through the use of standard fk relationships. I'm trying to figure out how to setup my controller and views to display the contents of these other tables/models from within the main view.
I apologize if it's a bit confusing, but here's an example. I have a table employees and I'm attempting to list all the emails for that employee in my detail view, the emails are stored in email_manager and there is a foreign key that references the employee_id column from the employees table. My employee model looks something like this:
[Table("employee.employees")]
public partial class employees1
{
public employees1()
{
employee_email_manager = new HashSet<email_manager>();
employee_employment_history = new HashSet<employment_history>();
employee_job_manager = new HashSet<job_manager>();
employee_phone_manager = new HashSet<phone_manager>();
this.salaries = new HashSet<salary>();
}
[Key]
public int employee_id { get; set; }
[Display(Name="Employee ID")]
public int? assigned_id { get; set; }
[Display(Name="Web User ID")]
public int? all_id { get; set; }
[Required]
[StringLength(50)]
[Display(Name="First Name")]
public string first_name { get; set; }
[StringLength(50)]
[Display(Name="Last Name")]
public string last_name { get; set; }
[Column(TypeName = "date")]
[Display(Name="Birthday")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime birth_day { get; set; }
[Required]
[StringLength(1)]
[Display(Name="Gender")]
public string gender { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Social")]
public string social { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Address")]
public string address_line_1 { get; set; }
[StringLength(50)]
[Display(Name="Suite/Apt#")]
public string address_line_2 { get; set; }
[Required]
[StringLength(40)]
[Display(Name="City")]
public string city { get; set; }
[Required]
[StringLength(20)]
[Display(Name="State")]
public string state { get; set; }
[Required]
[StringLength(11)]
[Display(Name="Zip")]
public string zip { get; set; }
[Column(TypeName = "date")]
[Display(Name="Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime hire_date { get; set; }
[Column(TypeName = "date")]
[Display(Name="Separation Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? termination_date { get; set; }
[StringLength(70)]
[Display(Name="Emergency Contact Name")]
public string emergency_contact_name { get; set; }
[StringLength(15)]
[Display(Name = "Emergency Contact Number")]
public string emergency_contact_phone { get; set; }
[Display(Name = "Notes")]
public string notes { get; set; }
public virtual all_employees all_employees { get; set; }
public virtual ICollection<email_manager> employee_email_manager { get; set; }
public virtual ICollection<employment_history> employee_employment_history { get; set; }
public virtual ICollection<job_manager> employee_job_manager { get; set; }
public virtual ICollection<phone_manager> employee_phone_manager { get; set; }
public virtual ICollection<salary> salaries { get; set; }
And my email_manager model is:
[Table("employee.email_manager")]
public partial class email_manager
{
[Key]
public int email_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(255)]
public string email { get; set; }
public int email_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
public virtual email_types email_types { get; set; }
public virtual employees1 employees1 { get; set; }
}
[Table("employee.email_types")]
public partial class email_types
{
public email_types()
{
email_manager = new HashSet<email_manager>();
}
[Key]
public int email_type_id { get; set; }
[Required]
[StringLength(50)]
public string email_type_name { get; set; }
public virtual ICollection<email_manager> email_manager { get; set; }
}
Solving this one was actually an all day task for me, but I managed to finally crack the answer. It turns out that even though my foreign keys were mapped inside the the ApplicationDbContext, they weren't being mapped properly. This was causing me some serious headache, and it turns out it was heavily related to another question I asked Here.
To remedy this, I had to explicitly define my foreign key columns within each of my respective models, using [ForeignKey("FOREIGN_KEY_COLUMN")] directly above my collection housing the model with the respective primary key. The corrected version is similar to:
[Table("employee.email_manager")]
public partial class email_manager
{
[Key]
public int email_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(255)]
public string email { get; set; }
//[ForeignKey("email_type")]
public int email_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
[ForeignKey("email_type")]
public virtual email_types email_types { get; set; }
public virtual employees1 employees1 { get; set; }
}
[Table("employee.email_types")]
public partial class email_types
{
public email_types()
{
email_manager = new HashSet<email_manager>();
}
[Key]
public int email_type_id { get; set; }
[Required]
[StringLength(50)]
public string email_type_name { get; set; }
public virtual ICollection<email_manager> email_manager { get; set; }
}
Within the view, to reference the appropriate emails, you can then do something similar to:
<dt>
#Html.DisplayNameFor(model => model.employee_email_manager)
</dt>
<dd>
#foreach (var item in Model.employee_email_manager)
{
<text>#Html.DisplayFor(modelItem => item.email_types.email_type_name): </text>
#Html.DisplayFor(modelItem => item.email)
<br />
}
</dd>
This change didn't require changing my employees1 model in any way, only the referenced models such as email_manager, phone_manager, etc.
I am building a reservation system. I have users in roles('admin', 'client', 'employee', 'student').
Each reservation must be associated with a user of role client, it might be assigned to user of role employee and might also be assigned to user of role student.
So in my reservation class I have properties of type User and I have marked them with [ForeignKey("AnytypeId")] attribute to hint EF for relations.
I have seen code like this at http://blog.stevensanderson.com/2011/01/28/mvcscaffolding-one-to-many-relationships/
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public Service Service
{
get;
set;
}
public string EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public User Employee { get; set; }
public string ClientId { get; set; }
[ForeignKey("ClientId")]
public User Client { get; set; }
public string StudentId { get; set; }
[ForeignKey("StudentId")]
public User Student { get; set; }
}
public class User
{
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//public Guid UserId { get; set; }
[Key]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "User Name")]
[MaxLength(100)]
public string UserName { get; set; }
[Required]
[MaxLength(64)]
public byte[] PasswordHash { get; set; }
[Required]
[MaxLength(128)]
public byte[] PasswordSalt { get; set; }
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[MaxLength(200)]
public string Email { get; set; }
[MaxLength(200)]
public string Comment { get; set; }
[Display(Name = "Approved?")]
public bool IsApproved { get; set; }
[Display(Name = "Crate Date")]
public DateTime DateCreated { get; set; }
[Display(Name = "Last Login Date")]
public DateTime? DateLastLogin { get; set; }
[Display(Name = "Last Activity Date")]
public DateTime? DateLastActivity { get; set; }
[Display(Name = "Last Password Change Date")]
public DateTime DateLastPasswordChange { get; set; }
public string address { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Phone { get; set; }
public bool? IsActive { get; set; }
public int? ClientTypeID { get; set; }
public virtual ClientType ClientType { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public DateTime? PackageValidity { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(m =>
{
m.ToTable("RoleMemberships");
m.MapLeftKey("Username");
m.MapRightKey("RoleName");
});
}
}
Now as I run my mvc3 EF code first app database created for me on the fly with following ERD and edmx model.
Now few problems that I am having:
1. When I am listing all the users of role clients their reservation property is showing always 0 even if their are reservations available in database.
2. If I am trying to delete a user of role client who have reservation in database I get following error.
The DELETE statement conflicted with the REFERENCE constraint "Reservation_Client". The conflict occurred in database "CRSDB", table "dbo.Reservations", column 'ClientId'.
The statement has been terminated.
I checked the realtions in ERD and edmx model their is no cascade delete applied to them. How can I instruct EF to delete all the reservations when deleting user of role client but not for users of role employee or student.
This code does the trick
public class Reservation
{
public int ReservationID
{
get;
set;
}
[Required(ErrorMessage="Please provide a valid date")]
public DateTime ReservationDate
{
get;
set;
}
public DateTime ReservationEnd { get; set; }
public DateTime EntryDate
{
get;
set;
}
public DateTime UpdatedOn
{
get;
set;
}
public decimal Ammount
{
get;
set;
}
public decimal? Discount { get; set; }
[DataType(DataType.MultilineText)]
public string ServiceDetails { get; set; }
[DataType(DataType.MultilineText)]
public string Remarks { get; set; }
public String PaymentMethod { get; set; }
public string VoucherNumber { get; set; }
public int ServiceID
{
get;
set;
}
public virtual Service Service
{
get;
set;
}
public string EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual User Employee { get; set; }
public string ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual User Client { get; set; }
public string StudentID { get; set; }
[ForeignKey("StudentID")]
public virtual User Student { get; set; }
}
public class ReservationMap : EntityTypeConfiguration<Reservation>
{
public ReservationMap()
{
this.HasOptional(r => r.Client).WithMany().WillCascadeOnDelete(true);
this.HasOptional(r => r.Employee).WithMany().WillCascadeOnDelete(false);
this.HasOptional(r=>r.Student).WithMany().WillCascadeOnDelete(false);
}
}