MVC-4 Assigning Employees and Manager to Department Scenerio and EF-CodeFirst - sql-server

I have a Department Table with Fields
public class Department
{
[ScaffoldColumn(false)]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(100)]
public string DepartmentName { get; set; }
public bool Active { get; set; }
public int LocationID { get; set; }
public virtual Location UsersCompanyLocation { get; set; }
}
and an Employee Table
public class Employee
{
[ScaffoldColumn(false)]
[Key]
public int UserId { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(50)]
public string FirstName { get; set; }
[StringLength(50)]
public string LastName { get; set; }
public string UserName { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(50)]
public string IDCardNo { get; set; }
[StringLength(50)]
public string Address { get; set; }
[StringLength(50)]
public string City { get; set; }
[StringLength(50)]
public string Zip { get; set; }
[StringLength(50)]
public string Mobile { get; set; }
[StringLength(50)]
public string HomePhone { get; set; }
public int? DesignationId { get; set; }
public Designations EmployeeDesignation { get; set; }
public int? DepartmentID { get; set; }
public virtual Department UserDepartment { get; set; }
[Display(Name = "Company", ResourceType = typeof(Translations.Translation))]
public int CompanyID { get; set; }
public virtual Company UserCompany { get; set; }
public int? LocationID { get; set; }
public virtual Location UsersCompanyLocation { get; set; }
[StringLength(500)]
[Display(Name = "Pic", ResourceType = typeof(Translations.Translation))]
public string Pic { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Date)]
[Display(Name = "HireDate", ResourceType = typeof(Translations.Translation))]
public DateTime HireDate { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Date)]
[Display(Name = "DateofBirth", ResourceType = typeof(Translations.Translation))]
public DateTime DOB { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(50)]
[Display(Name = "MaritalStatus", ResourceType = typeof(Translations.Translation))]
public string MaritialStatus { get; set; }
[StringLength(50)]
public string AccountNumber { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(256)]
[DataType(DataType.EmailAddress, ErrorMessage = "*")]
public string PersonalEmail { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(256)]
[DataType(DataType.EmailAddress, ErrorMessage = "*")]
public string OfficialEmail { get; set; }
public int? RoleId { get; set; }
public virtual Roles UserRole { get; set; }
public int? EmploymentStatusID { get; set; }
public virtual Employment EmploymentStatus { get; set; }
}
Now my Scenerio is thatI want To Assign one Employee as Manager to a Department and from the remaining pool of Employees, i may assign Employees to That Department. I am using code first EF technique, I am not able to make a proper class to work with this scenerio. Secondly I want to use List Box twice, first from which we may select just 1 employee as Manager and Second from which I want to select multiple employees from the remaing pool of Employees. Can any one help me in this scenerio
I have done the database portion after using up the whole day
I have to make another table (offcourse a class in EF CodeFirst) "DepartmentManager"
public class DepartmentManager
{
[ScaffoldColumn(false)]
public int ID { get; set; }
public int DepartmentId { get; set; }
public virtual Department AssignedDepartment { get; set; }
public int UserID { get; set; }
public virtual Employee ManagerialEmployee { get; set; }
public virtual List<DepartmentEmployees> DepartmentEmployees { get; set; }
This table has A UserID foreign key, Now for assignig employees to the Department, i will make another table "DepartmentEmployees" with composite keys
public class DepartmentEmployees
{
[ScaffoldColumn(false)]
[Key, Column(Order = 0)]
public int ID { get; set; }
[ScaffoldColumn(false)]
[Key, Column(Order = 1)]
public int EmployeeId { get; set; }
}
Now two things to ask, how to make foreign key UserID unique so that it may not be repeated, 2nd how to use List Box such that in one List Box just one Employee is Selected and in 2nd one, we may select the remainging employees, and how to fill the 2nd List Box such that an employee which has been selected as Manager doesn't appear in the 2nd List Box ??????????????

Related

Convert query from SQL to Entity Framework code first approach

I want to convert my SQL query into Entity Framework code-first but unable to do it.
This is my SQL query
select * from tests where id in(select testid from PatientTests where PatientId=#id)
This is Test Model from this model I want to fetch records.
public class Tests
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Test Name")]
public string TestName { get; set; }
[Display(Name = "Short Name")]
public string ShortName { get; set; }
[Display(Name="Technical Name")]
public string TechName { get; set; }
[Required]
[Display(Name ="Test Price")]
public float TestPrice { get; set; }
[Display(Name = "Sub Department")]
public int SubDeptId { get; set; }
[Display(Name = "Center")]
public int CenterId { get; set; }
public string Separate { get; set; }
[Display(Name = "Sub Department")]
[ForeignKey("SubDeptId")]
//relation of departments table
public virtual SubDepartments subDepartments { get; set; }
[Display(Name = "Centers")]
[ForeignKey("CenterId")]
//relation of departments table
public virtual Centers centers { get; set; }
}
this is patient tests model
public class PatientTest
{
[Key]
public int Id { get; set; }
[Display(Name ="Patient Id")]
public int PatientId { get; set; }
[Display(Name ="Test Id")]
public int TestId { get; set; }
[Display(Name ="Doctor")]
public int DoctorId { get; set; }
[Display(Name="Center")]
public int CenterId { get; set; }
[Display(Name = "Test")]
[ForeignKey("TestId")]
//relation of Tests table
public virtual Tests Tests { get; set; }
[Display(Name = "Doctor Reference")]
[ForeignKey("DoctorId")]
//relation of Doctors table
public virtual Doctors Doctors { get; set; }
[Display(Name = "Center Reference")]
[ForeignKey("CenterId")]
//relation of Centers table
public virtual Centers Centers { get; set; }
[Display(Name = "Patient")]
[ForeignKey("PatientId")]
//relation of Patient table
public virtual Patient Patient { get; set; }
}
So I want record from tests table where id should be matched with patientTest table testid and only given patient Id record must be fetch.
Your Tests model seems to be missing a navigation property to PatientTest. It can still be done though.
Guessing a bit here for how your context properties are named.
var tests = context.PatientTests
.Where(pt => pt.PatientId == patientId)
.Select(pt => pt.Tests)
.ToList();

The INSERT statement conflicted with the FOREIGN KEY. Entity includes ForeignKey Id property

I'm doing one to many relationship database with Entity Framework with an Id property.
I have two model classes:
public class PersonModel
{
[Key]
public int PersonId { get; set; }
public string NickName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int TeamRefId { get; set; }
[ForeignKey("TeamRefId")]
public virtual TeamModel TeamModel { get; set; }
}
public class TeamModel
{
public TeamModel()
{
TeamMembers = new List<PersonModel>();
this.Tournaments = new HashSet<TournamentModel>();
}
[Key]
public int TeamId { get; set; }
public string TeamName { get; set; }
public virtual ICollection<PersonModel> TeamMembers { get; set; }
public virtual ICollection<TournamentModel> Tournaments { get; set; }
public virtual MatchUpEntryModel MatchupEntry { get; set; }
public virtual MatchUpModel Matchup { get; set; }
}
When I'm trying to create a new Person entity, I get this error:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.PersonModel_dbo.TeamModel_TeamRefId". The conflict occurred in database "Tournament2", table "dbo.TeamModel", column 'TeamId'.
Making Foreign Key in Person Model nullable should solve your problem
note that created person will have No Team until you Modify it later after your create Team
public class PersonModel
{
[Key]
public int PersonId { get; set; }
public string NickName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int? TeamRefId { get; set; }
[ForeignKey("TeamRefId")]
public virtual TeamModel TeamModel { get; set; }
}

Invalid object name 'dbo.customers1'

I'm getting the error "Invalid object name 'dbo.customers1'" on my view...
#foreach (var item in Model)
{
<tr>
<td>#item.orderid</td>
<td>#item.customer.firstname</td>
I have the ViewModel classes...
public class orders
{
[Key]
public int orderid { get; set; }
public System.DateTime createdate { get; set; }
public string createdby { get; set; }
public Nullable<int> statusid { get; set; }
public Nullable<System.DateTime> pickup { get; set; }
public Nullable<System.DateTime> dropoff { get; set; }
public Nullable<System.DateTime> scheduledout { get; set; }
public Nullable<System.DateTime> scheduledin { get; set; }
public bool instorepickup { get; set; }
public string paymenttype { get; set; }
public System.DateTime reservationstart { get; set; }
public System.DateTime reservationend { get; set; }
public bool morningpickup { get; set; }
public Nullable<int> customerid { get; set; }
public string notes { get; set; }
public string shippingtype { get; set; }
public Nullable<decimal> shippingestimate { get; set; }
public virtual customer customer { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual orderstatuses orderstatuses { get; set; }
public virtual ICollection<serialorders> serialorders { get; set; }
}
and
public class customers
{
[Key]
public int customerid { get; set; }
public System.DateTime createdate { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
[Required]
public string billingaddress1 { get; set; }
public string billingaddress2 { get; set; }
[Required]
public string billingcity { get; set; }
public string billingstate { get; set; }
[Required]
public string billingzip { get; set; }
[Required]
public string billingcountry { get; set; }
public string phone { get; set; }
[Required]
public string email { get; set; }
[Required]
public string shippingaddress1 { get; set; }
public string shippingaddress2 { get; set; }
[Required]
public string shippingcity { get; set; }
public string shippingstate { get; set; }
[Required]
public string shippingzip { get; set; }
[Required]
public string shippingcountry { get; set; }
public bool goodstanding { get; set; }
public string userid { get; set; }
public Nullable<DateTime> insuranceexp { get; set; }
public virtual ICollection<invoice> invoices { get; set; }
public virtual ICollection<order> orders { get; set; }
}
this is my model...
And I have a data access layer...
public DbSet<tvc.viewModels.orders> orders { get; set; }
public DbSet<tvc.viewModels.customers> customers { get; set; }
The error is pretty straight-forward. There's no dbo.customers1 table in your database. As to why, there's really not enough information here to say, but the most likely causes are:
You're using Database First or Code First with an existing database, and your entities are out of sync with the database.
You're using Code First, don't have migrations enabled, and you've made a change to either your entities or your database. Again, out of sync.
You've specified an explicit table name, either via the Table attribute or fluent config, that doesn't exist. Either way, change either the explicit table name to what it should be or rename your database table so it matches.
There was an oversight in my ViewModel. I was pointing customer, which is the name of the database table and the model class, rather than the viewmodel class which is customers (with an s).

Entity Framework: Unable to determine the principal end of the relationship. Multiple added entities may have the same primary key

I'm getting this error while updating the model I'm sharing my code, please tell me the best solution for this.
Ticket Detail Class:
public class TicketDetail
{
[Key]
public int TicketDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? CustomerPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Ticket Ticket { get; set; }
}
OrderDetailClass:
public class OrderDetail
{
[Key]
public int OrderDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? UnitPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Order Order { get; set; }
}
Order Class:
public class Order : GenericOrder
{
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Ticket Class
public class Ticket : GenericOrder
{
public virtual ICollection<TicketDetail> TicketDetails { get; set; }
}
GenericOrderClass:
public abstract class GenericOrder
{
[Key]
public int GenericOrderId { get; set; }
public string ProcessId { get; set; }
public DateTime Date { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
public decimal Total { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and this is the controller class code
TryUpdateModel(order);
TryUpdateModel(ticket);
try
{
order.Date = DateTime.Now;
ticket.Date = DateTime.Now;
order.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
ticket.ProcessId = order.ProcessId;
//Add the Order
storeDB.Orders.Add(order);
storeDB.Tickets.Add(ticket);
//Process the order
cart.CreateOrder(order);
cart.CreateTicket(ticket);
// Save all changes
storeDB.SaveChanges();
//return RedirectToAction("Complete",
// new { id = order.QuoteOrderId });
TempData["OrderSuccess"] = "Your order has been submitted successfully with the Process ID " + order.ProcessId;
TempData["OrderId"] = order.GenericOrderId;
TempData["Email"] = order.Email;
return RedirectToAction("Confirm");
}
catch (Exception e)
{
//Invalid - redisplay with errors
ModelState.AddModelError("", e.Message);
return View(order);
}
I have searched internet but couldn't find any solution.
Try saving Order and Ticket and after they are saved add Details to them.

How to generate a unique GUID when creating a new object in Entity Framework 5?

I've similar questions that refer to this annotation to solve their problem:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
However, applying this to my relevant Entity Model does nothing.
When I call the .Add() method, it inserts the GUID as 00000000-0000-0000-0000-000000000000.
As you can see, the annotation I mentioned is present in the model:
using System;
using System.Collections.Generic;
public partial class Event
{
[System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}
How can I generate a unique GUID upon inserting a new Entity Object?
You can always initialize the Guid in a constructor.
public partial class Event
{
public Event()
{
ID = Guid.NewGuid();
}
public System.Guid ID { get; set; }
public int AccountID { get; set; }
public string ExternalID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public Nullable<System.DateTime> StartTime { get; set; }
public Nullable<System.DateTime> EndTime { get; set; }
public Nullable<bool> AllDay { get; set; }
public Nullable<System.Guid> ImageData { get; set; }
public string ImageUrl { get; set; }
public virtual Account Account { get; set; }
public virtual FetchedFile FetchedFile { get; set; }
}

Resources