I am trying to create a database called Donation within it it got this column IC its is and identity number value so I had already set it into IsUnique but somehow it still return the error message
Donation_Customers_Target_Donation_Customers_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'IC' on entity 'Donation' does not match the type of property 'CustomerID' on entity 'Customers' in the referential constraint 'Donation_Customers'.
And here is the model of the Donation and Customers
Customer
[Key]
public int CustomerID { get; set; }
[Display(Name = "IC")]
[Index(IsUnique = true)]
[Required(AllowEmptyStrings = false, ErrorMessage = "IC is required")]
[MinLength(14)][MaxLength(14)]
public string IC { get; set; }
[Display(Name = "First Name")]
[Required(AllowEmptyStrings = false, ErrorMessage = "First name required")]
public string FirstName { get; set; }
Donation
[Key]
public int DonationId { get; set; }
public DateTime? TransacTime { get; set; }
public int Amount { get; set; }
public string IC { get; set; }
[ForeignKey("IC")]
public Customers Customers { get; set; }
Related
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();
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
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; }
}
public class Employee {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public decimal Salary { get; set; }
public string Email { get; set; }
}
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
When I'm adding Data Annotation [Required(ErrorMessage = "Employee Name is required")] to the Name property it's throwing an InvalidOperationException. As I was trying to fix the bug I'm getting these suggestions online:
It means one of your classes use in the EmployeeContext has changed, but the database hasn't been updated so is now out of date. You need to update this use Code First migrations.
When I'm making the following changes its throwing an error now
public class Employee {
[Key]
public int Id { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(35)]
public string Name { get; set; }
public string Address { get; set; }
public decimal Salary { get; set; }
public string Email { get; set; }
}
Snapshot:
Questions:
If a Database Table is created is it possible to change a column ?
When adding a Data Annotation Attribute it's throwing an Exception, why is the database table column not changing ?
Addicted to your tutorials now
User Migration for update database structure
Without [Required] filed Name allow null (varchar(x) null), with [Required] Name change not null (varchar(x) not null)
If in database threre are rows with nullable Name, can be error on update (with migration)
my models are as follows...
public class Company
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Fullname { get; set; }
public bool HasFuneralInsuranceParlours { get; set; }
public bool HasFuneralInsurancePolicies { get; set; }
public bool HasLifeInsurancePolicies { get; set; }
public bool IsDeleted { get; set; }
public virtual List<Office> Offices { get; set; }
}
public class Office
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(100)]
public string Address1 { get; set; }
[MaxLength(100)]
public string Address2 { get; set; }
[MaxLength(100)]
public string Address3 { get; set; }
[MaxLength(20)]
public string Telephone { get; set; }
[MaxLength(20)]
public string Fax { get; set; }
[MaxLength(255)]
public string Email { get; set; }
public bool IsDeleted { get; set; }
public Guid CompanyId { get; set; }
public virtual Company Companies { get; set; }
public virtual List<Employee> Employees { get; set; }
}
and controllers
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OfficeModel model)
{
bool success = false;
string message = "";
byte[] logo = null;
var user = SecurityHelper.GetAuthenticatedUser(this.HttpContext);
try
{
if (ModelState.IsValid)
{
if (model.Name.IsNullOrWhitespace()) throw new Exception("Unable to create this Employee Name. The Type cannot be blank or spaces.");
if (models.Offices.Any(x => x.Name.ToLower() == model.Name.ToLower())) throw new Exception(string.Format("This Office's Name '{0}' already exists. Please check your data.", model.Name.ToUpperCase()));
var entry = new Office
{
Id = Guid.NewGuid(),
Name = model.Name.ToUpperCase(),
Address1 = model.Address1.ToUpperCase(),
Address2 = model.Address2.ToUpperCase(),
Address3 = model.Address3.ToUpperCase(),
Telephone = model.Telephone.ToUpperCase(),
Fax = model.Fax.ToUpperCase(),
Email = model.Email.ToUpperCase(),
IsDeleted = false,
CompanyId = user.CompanyId,
Bankings = new List<Banking>()
{
new Banking
{
Bank = model.OfficeBank.ToUpperCase(),
Account = model.BankAccount.ToUpperCase(),
Branch = model.Branch.ToUpperCase(),
BranchNo = model.BranchNo.ToUpperCase(),
AccountType = model.AccountType.ToUpperCase()
}
}
};
models.Offices.Add(entity);
success = true;
return RedirectToAction("Index");
}
else
{
message = "An error was cought please check your data and retry";
}
}
catch (Exception ex)
{
message = ex.Message;
}
return View(model);
}
when l debug the above code l return the following error
"The INSERT statement conflicted with the FOREIGN KEY constraint
\"FK_dbo.Offices_dbo.Companies_CompanyId\". The conflict occurred in
database \"PolicyManager\", table \"dbo.Companies\", column
'Id'.\r\nThe statement has been terminated."
When l hover model.Name l am return a value but the rest return me a null value which l suspect the thus the cause of the the above error.
What problem can it possible be because l have used the similar code before and it worked. May anyone help. Thank you in advance
You are adding a New Office.
The error says that there is a referential integrity problem With the Foreign key constraint to the Company table.
When you create the Order you add the following Company key:
CompanyId = user.CompanyId
So it appears that user.CompanyId is not an id that is registered against an existing Company.