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

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; }

Related

How do I remove a Foreign Key from Code First?

I have two Models. A Bike, and Reservation.
Bike:
public class Bike
{
public int Id { get; set; }
public BikeType Type { get; set; }
public BikeGender Gender { get; set; }
public BikeSize Size { get; set; }
public string Brand { get; set; }
public double HourRate { get; set; }
public double DailyRate { get; set; }
public virtual Store Store { get; set; }
[ForeignKey("Store")]
public int Store_Id { get; set; }
}
and Reservation:
public class Reservation
{
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual Customer Customer { get; set; }
[ForeignKey("Customer")]
public int Customer_Id { get; set; }
public virtual List<Bike> Bikes { get; set; }
public Reservation()
{
Bikes = new List<Bike>();
}
}
When I create the database from Code First it adds a column in the 'Bikes' table called: 'Reservation_Id'.
Click to view image of the problem
The problem comes when I create a new Reservation, The bike which I choose gets the 'Reservation_Id' of the Id from Reservation. So when I try to delete this Reservation I get an error:
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_dbo.Bikes_dbo.Reservations_Reservation_Id". The
conflict occurred in database "BikeRental.Model.BikeShopDataModel",
table "dbo.Bikes", column 'Reservation_Id'.
The code that I use to delete the reservation:
Click here to view the reservation delete code
How can I fix that I can just delete the reservation without interfering with the unique key? Or how do I delete the whole unique key from the table?
There is a One to Many relationship between Bike and Reservation.
EfCore or EF needs a ForeignKey on the Many side. When u did not define the ForeignKey on the rigth side, EF is gonna block you because that Reservation object dependent on the Bike object. Your mistake is defining that relationship in the wrong side.
Bike class should be like :
public class Bike
{
public int Id { get; set; }
public BikeType Type { get; set; }
public BikeGender Gender { get; set; }
public BikeSize Size { get; set; }
public string Brand { get; set; }
public double HourRate { get; set; }
public double DailyRate { get; set; }
public virtual Store Store { get; set; }
public List<Reservation> Reservations{get;set;}
[ForeignKey("Store")]
public int Store_Id { get; set; }
}
Reservation class should be like:
public class Reservation
{
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual Customer Customer { get; set; }
[ForeignKey("Customer")]
public int Customer_Id { get; set; }
public virtual Bike Bike { get; set; }
[ForeignKey("Bike")]
public int Bike_Id { 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.

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.

Foreignkey Name error in Entity Framework Code First

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

Categories