Convert query from SQL to Entity Framework code first approach - sql-server

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();

Related

SQL Server the column name is specified more than once in the set clause. Entity framework issue

When I do an insert using EF6, I get this error
The column name 'employee_id' is specified more than once in the SET clause. A column cannot be assigned more than one value in the same SET clause. Modify the SET clause to make sure that a column is updated only once. If the SET clause updates columns of a view, then the column name 'employee_id' may appear twice in the view definition
My models looked like this:
public class Entity
{
public Entity()
{
IsActive = true;
IsDeleted = false;
DateCreated = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public int CompanyID { get; set; }
public int SubID { get; set; }
public DateTime DateCreated { get; set; }
public bool IsTransient()
{
return EqualityComparer<long>.Default.Equals(ID, default(long));
}
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
}
public partial class NextOfKin : Entity
{
[Required]
public long employee_id { get; set; }
[StringLength(100)]
[Required]
public string nok_first_name { get; set; }
[StringLength(100)]
[Required]
public string nok_last_name { get; set; }
[StringLength(300)]
[Required]
public string nok_address { get; set; }
[StringLength(100)]
public string nok_email { get; set; }
[StringLength(100)]
public string nok_phone { get; set; }
[StringLength(100)]
public string nok_employer { get; set; }
[StringLength(300)]
public string nok_work_address { get; set; }
[StringLength(100)]
[Required]
public string nok_relationship { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee : Entity
{
//Person Records
public long UserId { get; set; }
public int TitleId { get; set; }
public int? ReligionId { get; set; }
public string SerialNo { get; set; }
[StringLength(100)]
[Required]
public string FirstName { get; set; }
[StringLength(100)]
[Required]
public string LastName { get; set; }
}
My insert code into next of kin was like this.
NextOfKin nextOfKin = new NextOfKin();
nextOfKin.employee_id = newEmployee.ID;
nextOfKin.nok_first_name = "Friday";
nextOfKin.nok_last_name = "Ben";
nextOfKin.nok_address = "XXX";
nextOfKin.nok_email = "xa#xo.com";
nextOfKin.nok_phone = "023938494";
nextOfKin.nok_employer = "50 Queens Street";
nextOfKin.nok_work_address = "51 Queens Street";
nextOfKin.nok_relationship = "Neighbour";
db.NextOfKins.Add(nextOfKin);
db.SaveChanges();
I got an error like this using EF Core
'PropertyNameID' is specified more than once in the SET clause or
column list of an INSERT. A column cannot be assigned more than one
value in the same clause. Modify the clause to make sure that a column
is updated only once. If this statement updates or inserts columns
into a view, column aliasing can conceal the duplication in your code.
It turned out that I had the case wrong in my relatonship
In My business object I had the foreign key set with the wrong case.
public int PropertyNameID { get; set; }
[ForeignKey("PropertyNameId")] public virtual PropertyNameExt PropertyName { get; set; }
Should have been
[ForeignKey("PropertyNameID")] public virtual PropertyNameExt PropertyName { get; set; }
To fix this, remove the relationship on next of kin model, then do migration.
To remove, remove public virtual Employee Employee { get; set; } from NextOfKin model.
The reason for this issue is as follow:
Relationships are only created properly if you name the reference property properly. In this case you should use EmployeeID instead of employee_id for the relationship between next of kin and employee.
The Employee model does not have a link back to the next of kin model. If it's a one to many you can add the property below to the Employee model.
public virtual List NextOfKins{get; set;} //if you need lazy loading
or
public List NextOfKins{get; set;} //if you don't need lazy loading

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.

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

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 ??????????????

Resources