Foreignkey Name error in Entity Framework Code First - c#

When I'm using the following code, the tables are generated successfully with the Primary key and Foreign Key relations.
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public virtual DepartmentModel DID { get; set; }
}
But when I use the following Code, I'm Getting error:
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
ERROR:
The ForeignKeyAttribute on property 'DID' on type
'MvcApplication1.Models.EmployeeModel' is not valid. The foreign key
name 'DeptID' was not found on the dependent type
'MvcApplication1.Models.EmployeeModel'. The Name value should be a
comma separated list of foreign key property names.
Please Help. Thanks in advance.

The problem is with your EmployeeModel as you are missing departmentid field in your table as suggested by Gert. you can use the below for EmployeeModel
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DeptID { get; set; } //<-- You forgot to add this
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}

Put the foreign key as a property inside your model then have the navigation property point to it.
public class EmployeeModel
{
[Key]
public int ID { get; set; }
public int DeptID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}

In '[ForeignKey("DeptID")]' you need to have the property DeptID in the model.
If you don't want it but just the name DeptID on the foreign key field you need to use fluent interface to configure the relationship i.e.
HasOptional(t => t.DID)
.WithMany()
.Map(d => d.MapKey("DeptID"));

Related

The INSERT statement conflicted with the FOREIGN KEY (Code First Approach)

These are my classes:
public class Animal
{
[Key]
public int AnimalId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Img { get; set; }
public string Description { get; set; }
public List<Comment> comments { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public Animal Animal { get; set; }
List<Animal> animals { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string Text { get; set; }
public int AnimalId { get; set; }
public Animal Animal { get; set; }
}
I'm getting this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_animals_categories_CategoryId". The conflict occurred in database "Local_PetShop", table "dbo.categories", column 'CategoryId'.
I can't save the changes in the data base even when I insert a categoryid value in the animal creation page.
Any ideas?
You need to setup your Primary Keys on all tables.
for example
[Key]
public int CategoryId { get; set; }

Foreign key accept null values

How can I make the foreign key of a table "PRODUCT" accept null values?
I require that at the time of filling the PRODUCT form you can save the information without having to select the bank. I generate the form PRODUCT(Controller) with entity framework
The foreign key del model Product -> "public int EntidadID { get; set; }"
I have two related models.
public class Product
{
[Key]
public int ProductID { get; set; }
public string NumContrato { get; set; }
public float TasaReal { get; set; }
public decimal Capital { get; set; }
public DateTime FechaValor { get; set; }
public DateTime FechaVencimiento { get; set; }
public int Plazo { get; set; }
public int BankID { get; set; }
public virtual CATbank CATbank { get; set; }
}
public class CATbank
{
[Key]
public int BankID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Is BankID your foreign key?
If so, in the Product class try changing
public int BankID { get; set; }
to
public int? BankID { get; set; }
and in your database table make sure that the field is nullable.

How to use 2 entity tables together?

I am working on school project which is about showing some database properties that I learned.I have 2 entity classes called Person and CarInformation.I want to show Name, Location,WhishedDays from Person and Brand, PlateNumber from CarInformation,together.
I tried generating new class called then I grouped Name, Location, WishedDays,Brand,PlateNumber.In the corresponding controller, I made a List with Select function but failed.
CarInformation Entity Class
public int Id { get; set; } //Primary key of carinfo table
public string Brand{ get; set; }
public string PlateNumber { get; set; }
public int Milage { get; set; }
public string InsuranceCompany{ get; set; }
public double ConsumptionPerMile { get; set; }
public int DailyPrice { get; set; }
public DateTime AvailableDates { get; set; }
[ForeignKey("Persons")]
public int OwnerId { get; set; } //foregein key (Person table to carinfo table)
public virtual Person Persons { get; set; } //Navigation property
public List<Sales> Sales { get; set; }
Person Entity Class
public int Id { get; set; } //primary key of person table
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public virtual CarInformation Cars { get; set; } //Navigation property
public List<CarInformation> cars { get; set; } //bir insana ait birden fazla araba olabilir
public List<Sales> sales { get; set; }
Person-CarInformation Class
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public string Brand { get; set; }
public string PlateNumber { get; set; }
Corresponding controller`s Index Method
public ActionResult Index()
{
var isimler = db.People.
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});
return View(isimler.ToList());
}
When I execute in this circumstances I get this result
Brand and PlateNumber is empty.
Any advises?
Thank You.
https://imgur.com/D9a8whD
You haven't included dependent entity while fetching data. You can get it by changing your code like shown below.
var isimler = db.People.Include("Cars").
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});

Entity Framework error when creating foreign keys

I'm attempting to use migrations to generate my EF database, but I'm getting a couple of errors when I'm executing the update-database command.
Error 1
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Occupier] (
[OccupierId] int NOT NULL IDENTITY,
[Title] int NOT NULL,
[FirstName] nvarchar(32) NULL,
[LastName] nvarchar(32) NULL,
[Dob] datetime2 NOT NULL,
[Relationship] nvarchar(32) NULL,
CONSTRAINT [PK_Occupier] PRIMARY KEY ([OccupierId]),
CONSTRAINT [FK_Occupier_Property_OccupierId] FOREIGN KEY ([OccupierId]) REFERENCES [Property] ([PropertyId]) ON DELETE CASCADE
);
Error 2
Cascading foreign key 'FK_Occupier_Property_OccupierId' cannot be created where the referencing column 'Occupier.OccupierId' is an identity column.
Could not create constraint or index. See previous errors.
From what I can see I have my tables set up correctly, but there's obviously something missing which I can't see. I'll post the code for the tables below and hopefully someone can see what I'm missing.
For clarity; a SolicitorInstruction has a Property object, which may contain a number of Occupiers.
I'm also not sure about the way [ForeignKey("string")] works. Is this saying "this is a foreign key to primary key "string"? or "string" is a foreign key?
SolicitorInstruction
public class SolicitorInstruction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SolicitorInstructionId { get; set; }
public InstructionTypes InstructionType { get; set; }
public int ApplicationId { get; set; }
public DateTime DateLogged { get; set; }
[ForeignKey("AdditionalInformationId")]
public AdditionalInformation AdditionalInformation { get; set; }
[ForeignKey("BorrowerBankId")]
public BorrowerBank BorrowerBank { get; set; }
[ForeignKey("BrokerId")]
public Broker Broker { get; set; }
[ForeignKey("PropertyId")]
public Property Property { get; set; }
[ForeignKey("SolicitorId")]
public Solicitor Solicitor { get; set; }
[ForeignKey("BorrowerId")]
public List<Borrower> Borrower { get; set; }
[ForeignKey("CurrentLenderId")]
public List<CurrentLender> CurrentLender { get; set; }
}
Property
[Table("Property")]
public partial class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PropertyId { get; set; }
[StringLength(8)]
public string ReferenceNumber { get; set; }
[StringLength(4)]
public string CaseOwner { get; set; }
public int AmountBorrowed { get; set; }
[ForeignKey("SecurityAddressId")]
public Address Security { get; set; }
[ForeignKey("CorrespondenceAddressId")]
public Address Correspondence { get; set; }
[ForeignKey("OccupierId")]
public List<Occupier> Occupier { get; set; }
public TenureTypes Tenure { get; set; }
public JurisdictionTypes Jurisdiction { get; set; }
public FunderTypes Funder { get; set; }
public Property()
{
Occupier = new List<Occupier>();
}
}
Occupier
[Table("Occupier")]
public partial class Occupier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OccupierId { get; set; }
public Honorifics Title { get; set; }
[StringLength(32)]
public string FirstName { get; set; }
[StringLength(32)]
public string LastName { get; set; }
public DateTime Dob { get; set; }
[StringLength(32)]
public string Relationship { get; set; }
}
Try this changes to add the navigation property in the dependent class.
Property
[Table("Property")]
public partial class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PropertyId { get; set; }
[StringLength(8)]
public string ReferenceNumber { get; set; }
[StringLength(4)]
public string CaseOwner { get; set; }
public int AmountBorrowed { get; set; }
[ForeignKey("SecurityAddressId")]
public Address Security { get; set; }
[ForeignKey("CorrespondenceAddressId")]
public Address Correspondence { get; set; }
public List<Occupier> Occupier { get; set; }
public TenureTypes Tenure { get; set; }
public JurisdictionTypes Jurisdiction { get; set; }
public FunderTypes Funder { get; set; }
public Property()
{
Occupier = new List<Occupier>();
}
}
Occupier
[Table("Occupier")]
public partial class Occupier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OccupierId { get; set; }
public Honorifics Title { get; set; }
[StringLength(32)]
public string FirstName { get; set; }
[StringLength(32)]
public string LastName { get; set; }
public DateTime Dob { get; set; }
[StringLength(32)]
public string Relationship { get; set; }
[Required]
public int PropertyId { get; set; }
[ForeignKey(PropertyId)]
public Property Property {get; set;}
}

Error: introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

A quick question for masters.
I got 2 EF model classes:
public class School
{
public int Id { get; set; }
[DisplayName("School")]
public string Name { get; set; }
public List<Teacher> Teachers { get; set; }
public List<Note> Notes { get; set; }
}
public class Teacher
{
public int Id { get; set; }
[DisplayName("Öğretmen")]
public string Name { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
public List<Note> Notes { get; set; }
}
Basically I want to create an one to many relationship in code-first.
But when I try to do that, I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.Teachers_dbo.Schools_SchoolId' on table 'Teachers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Where have I made a mistake?
EDIT
public class Note
{
public int Id { get; set; }
[Required,DisplayName("Başlık"), StringLength(50)]
public string Title { get; set; }
[Required,DisplayName("Açıklama"), StringLength(4000)]
public string Description { get; set; }
public string File { get; set; }
public DateTime UploadDate { get; set; }
public bool IsApproved { get; set; }
public int SchoolId { get; set; }
public int OwnerId { get; set; }
public int TeacherId { get; set; }
//Keys
public School School { get; set; }
public Teacher Teacher { get; set; }
public List<Comment> Comments { get; set; }
}
I didnt get any error for this Model and Keys..
Remove the relationship from Note to School and vice versa. You could get the school by the teacher that has a relationship to the note.
It will produce your issue.

Categories