I am trying to create a (in my opinion) quite simple setup, but I can't figure out why I keep getting this error when I run Update-Database:
Introducing FOREIGN KEY constraint 'FK_dbo.Breweries_dbo.Pages_PageId' on table 'Breweries' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I am trying to setup this structure:
Brewery > Page > IdentityUser
This is my classes:
public class Brewery
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Guid BreweryId { get; set; }
[Required]
public string Name { get; set; }
[Required]
[ForeignKey("Page")]
public Guid PageId { get; set; }
public virtual Page Page { get; set; }
public virtual ICollection<Image> Images { get; set; }
}
public class Page
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Guid PageId { get; set;}
[Required]
public string Title { get; set; }
public string Content { get; set; }
[Required]
[ForeignKey("CreatorUser")]
public string CreatorUserId { get; set; }
public virtual IdentityUser CreatorUser { get; set; }
}
I have seen a lot of other Stack Overflow posts and it seems like I should be setting something up in the OnModelCreating, but I can't get it right. I would like to avoid having a ICollection<Brewery> Breweries property on the Page, since I want many different entities to reference to the Page entity and it is irrelevant for a Page who is referencing to it.
I am new to Entity Framework and Code First so I might have approached this wrong without knowing. I would appreciate any help to setup the relationships correct.
As the association between Page and Brewery is required, EF defaults to cascaded delete. But if there are many entities referring to Page there will be multiple cascade paths and you have to override the default:
modelBuilder.Entity<Brewery>()
.HasRequired(b => b.Page)
.WithMany() // <= no inverse collection in Page.
.HasForeignKey(b => b.PageId)
.WillCascadeOnDelete(false);
You can only do this by fluent mapping. Also, this replaces the attributes on Brewery.PageId.
Related
I'm in a situation where one table has two One-None/One Relationships. How do I implement this using Entity Framework Code-First?
I've seen the following links
https://www.safaribooksonline.com/library/view/programming-entity-framework/9781449317867/ch04s07.html
https://cpratt.co/0-1-to-1-relationships-in-entity-framework/
https://www.tektutorialshub.com/one-to-one-relationship-entity-framework/
Where essentially it's said that the dependent end needs to have a primary key that is the same as that of the principal end. But I'm weary of implementing this with more than one One-None/One Relationship without confirmation and proper knowledge of what's going on. Furthermore I am not sure how to construct statements as it does not have a conventional Foreign Key.
I've also seen Configuring multiple 1 to 0..1 relationships between tables entity framework which confused me beyond recognition.
See below for the relevant part of my DB Diagram:
So Essentially, a Player shouldn't be saved without a DKImage, similarly a Product shouldn't be saved without a DKImage.
Below is the code for Models: Players, Products, DKImages (I know it's not correct, I only implemented it this way so I can generate the database and show the diagram)
Player
public enum Positions { PG, SG, SF, PF, C }
public class Player
{
[Key]
[ForeignKey("Images")]
public int PlayerID { get; set; }
[Required]
public string PlayerName { get; set; }
[Required]
public string PlayerLastName { get; set; }
[Required]
public int PlayerAge { get; set; }
[Required]
public Positions Position { get; set; }
[Required]
public bool Starter { get; set; }
[Required]
[Display(Name = "Active / Not Active")]
public bool Status { get; set; }
//Foreign Keys
public int PlayerStatsID { get; set; }
//Navigation Properties
[ForeignKey("PlayerStatsID")]
public virtual IQueryable<PlayerStats> PlayerStats { get; set; }
public virtual DKImages Images { get; set; }
}
DKImages
public class DKImages
{
[Key]
public int ImageID { get; set; }
[Required]
public string ImageURL { get; set; }
[Required]
public DateTime DateUploaded { get; set; }
//Foreign Keys
[Required]
public int CategoryID { get; set; }
//Navigation Properties
public virtual Products Products { get; set; }
public virtual Category Category { get; set; }
public virtual Player Player { get; set; }
}
Products
public class Products
{
[ForeignKey("Images")]
[Key]
public int ProductID { get; set; }
[Required]
public string ProductName { get; set; }
[Required]
public DateTime DateAdded { get; set; }
//Foreign Keys
[Required]
public int ProductTypeID { get; set; }
//Navigation Properties
[ForeignKey("ProductTypeID")]
public virtual ProductType ProductType { get; set; }
public virtual DKImages Images { get; set; }
}
Edit
I have been told that the code above is correct. If so then how do I create CRUD LINQ Statements (Or any method of constructing CRUD statements for that matter) with the above code.
What you want here is referred to as polymorphic associations: several entities having child entities of one type. They're typically used for comments, remarks, files etc. and usually applied to 1:n associations. In your case there are polymorphic 1:1 associations. Basically these associations look like this (using a bit more generic names):
How to implement them?
Entity Framework 6
In EF6 that's problem. EF6 implements 1:1 associations as shared primary keys: the child's primary key is also a foreign key to its parent's primary key. That would mean that there should be two FKs on Image.ID , one pointing to Person.ID and another one pointing to Product.ID. Technically that's not a problem, semantically it is. Two parent entities now own the same image or, stated differently, an image should always belong to two different parents. In real life, that's nonsense.
The solution could be to reverse the references:
But now there's another problem. The entity that's referred to is named the principal, the other entity is dependent. In the second diagram, Image is the principal, so in order to create a Person, its image must be inserted first and then the person copies its primary key. That's counter-intuitive and most likely also impractical. It's impossible if images are optional.
Nevertheless, since in your case you want images to be required let me show how this association is mapped in EF6.
Let's take this simple model:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Image Image { get; set; }
}
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Image Image { get; set; }
}
public class Image
{
public int ImgID { get; set; } // Named for distinction
public string Url { get; set; }
}
The required mapping is:
modelBuilder.Entity<Image>().HasKey(pd => pd.ImgID);
modelBuilder.Entity<Person>().HasRequired(p => p.Image).WithRequiredDependent();
modelBuilder.Entity<Product>().HasRequired(p => p.Image).WithRequiredDependent();
As you see, Image has two required dependents. Perhaps that's better than two required parents, but it's still weird. Fortunately, in reality it's not a problem, because EF doesn't validate these associations. You can even insert an image without a "required" dependent. I don't know why EF doesn't validate this, but here it comes in handy. The part WithRequiredDependent might as well have been WithOptional, it doesn't make a difference for the generated data model, but at least this mapping conveys your intentions.
An alternative approach could be inheritance. If Person and Product inherit from one base class this base class could be the principal in a 1:1 association with Image. However, I think this is abusing a design pattern. People and products have nothing in common. From a design perspective there's no reason for them to be part of one inheritance tree.
Therefore, in EF6 I think the most feasible solution is to use the third alternative: separate image tables per entity.
Entity Framework Core
In EF-core 1:1 associations can be implemented the EF6 way, but it's also possible to use a separate foreign key field in the dependent entity. Doing so, the polymorphic case looks like this:
The Image class is different:
public class Image
{
public Image()
{ }
public int ImgID { get; set; }
public int? PersonID { get; set; }
public int? ProductID { get; set; }
public string Url { get; set; }
}
And the mapping:
modelBuilder.Entity<Person>().Property(p => p.ID).UseSqlServerIdentityColumn();
modelBuilder.Entity<Person>()
.HasOne(p => p.Image)
.WithOne()
.HasForeignKey<Image>(p => p.PersonID);
modelBuilder.Entity<Product>().Property(p => p.ID).UseSqlServerIdentityColumn();
modelBuilder.Entity<Product>()
.HasOne(p => p.Image)
.WithOne()
.HasForeignKey<Image>(p => p.ProductID);
modelBuilder.Entity<Image>().HasKey(p => p.ImgID);
Watch the nullable foreign keys. They're necessary because an image belongs to either a Person or a Product. That's one drawback of this design. Another is that you need a new foreign key field for each new entity you want to own images. Normally you want to avoid such sparse columns. There's also an advantage as compared to the EF6 implementation: this model allows bidirectional navigation. Image may be extended with Person and Product navigation properties.
EF does a pretty good job translating this into a database design. Each foreign key has a filtered unique index, for example for Person:
CREATE UNIQUE NONCLUSTERED INDEX [IX_Image_PersonID] ON [dbo].[Image]
(
[PersonID] ASC
)
WHERE ([PersonID] IS NOT NULL)
This turns the association into a genuine 1:1 association on the database side. Without the unique index it would be a 1:n association from the database's perspective.
An exemple in your Player table would be this :
public class Player
{
// All the rest you already coded
[Required]
public int ImageID
[ForeignKey("ImageID")]
public virtual DKImage DKImage {get;set;}
}
This would force a player to have a DKImage, but as said in the comments, this create a one to many relationship.
Another way out would be to put all Player fields into the DKImage table, those fields would be null if there is no player associated to this DKImage.
Edit for 1 to 1..0
Ivan Stoev's link got some pretty interesting insight on how to accomplish this :
https://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations
It seems like you will have to put a bit more code in your class :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DKImage>().HasOptional(t => t.Player).WithRequired();
}
If the tutorial is correct, this would read as :
"DKImage entity has an optional association with one Player object but this association is required for Player entity".
I have not tested it yet.
I have a problem I am trying to solve with the Entity Framework 6.0 and hope someone here can give some direction on. I am much more comfortable with ADO.NET but want to do this project in EF.
I have an object called Policy and another called PayPlan
public class Policy
{
//Various properties not relevant
public PayPlan PaymentPlan { get; set; }
}
public class PayPlan
{
public int PayPlanId { get; set;}
public string Description { get; set; }
}
As you can see, in this example, a PayPlan is a child object for a Policy. It may be null, or there may be a single instance of a PayPlan associated with a policy.
When I run the model builder, it creates the tables and inserts a Foreign Key into the Policy Table for the record in the PayPlan. This doesnt really work for me though because 1) I would like to keep the Db schema similar to a previous version of the application wherein the PolicyId is a ForeignKey into the PayPlan and 2) With Cascading Deletes, if the PayPlan were to be deleted it would take the Policy with it and I need this to be the other way around. The Policy is the root object form which all other objects in the Db draw their relations. PayPlan, btw, is just a single example for this discussion but in the actual project the Policy object would contain a number of child objects associated with it in a similar manner.
My question, how do I set this up, either through Data Annotations or via the Fluent API, to achieve the schema I described?
If I understood your requirements correctly, you want to build model like this:
public class Policy {
[Key]
public int PolicyId { get; set; }
// this attribute is not required, but I prefer to be specific
// this attribute means navigation property PaymentPlan
// is "anoter end" of navigation property PayPlan.Policy
[InverseProperty("Policy")]
public virtual PayPlan PaymentPlan { get; set; }
}
public class PayPlan {
[Key]
public int PayPlanId { get; set; }
// define foreign key explicitly here
[ForeignKey("Policy")]
public int PolicyId { get; set; }
public virtual Policy Policy { get; set; }
public string Description { get; set; }
}
Update: the above works in EF Core, but does not work in EF 6. EF 6 treats this as one to many relationship (and is correct in that, because one Policy could have multiple PayPlans). To create one to (zero or) one relationship, you can create model like this:
public class Policy
{
[Key]
public int PolicyId { get; set; }
[InverseProperty("Policy")]
public virtual PayPlan PaymentPlan { get; set; }
}
public class PayPlan
{
[Key, ForeignKey("Policy")]
public int PolicyId { get; set; }
public Policy Policy { get; set; }
public string Description { get; set; }
}
So PayPlan doesn't have its own Id and instead has PolicyId which is both PK and FK. That way, only one (or none) pay plan may exist for one policy.
So, after digging a little bit about this on EF 6 after you mentioned you are using that version and found this:
Apparently alternate keys are not supported on EF 6. As #rowanmiller on this Github issue:
Unfortunately this is a limitation of EF6. You can not have a foreign
key property in a one-to-one relationship, unless it is also the
primary key property. This is essentially because EF6 doesn't support
alternate keys/unique indexes, so you can't enforce that a non-primary
key property is unique. The fact that you can do it when the foreign
key property isn't in the entity is a bit of a quirk... but obviously
not something we would remove :smile:.
BTW alternate keys (and therefore this scenario) is supported in EF
Core.
Mapping foreign key in HasOptional().WithOptionalDependent() relation
You can still have the FK as you want, but you can't have the FK property on your PayPlan class. If you do, you'll ended up with two FKs. So, if you configure your relationship like this:
public class Policy
{
public int PolicyId { get; set; }
public string Description { get; set; }
public PayPlan PaymentPlan { get; set; }
}
public class PayPlan
{
public int PayPlanId { get; set; }
public string Description { get; set; }
public Policy Policy { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PayPlan>()
.HasOptional(a => a.Policy)
.WithOptionalDependent(p => p.PaymentPlan)
.WillCascadeOnDelete(true);
}
You will end with this on SQL:
Didn't know about this since I never had this scenario. Sucks a lot. BUT you still can do it using EF core :), which is cool.
EF Core answer just for the record
You can solve this also using the FluentAPI. (I prefer the FluentApi rather than polluting my models with Attributes). Also, since you didn't mention which version of EF you are using, I assumed you are using EF Core.
public class Policy
{
public int PolicyId { get; set; }
public string Description { get; set; }
public PayPlan PaymentPlan { get; set; }
}
public class PayPlan
{
public int PayPlanId { get; set; }
public string Description { get; set; }
public Policy Policy { get; set; }
public int? PolicyId { get; set; }
}
Context class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Policy>()
.HasOne(a => a.PaymentPlan)
.WithOne(b => b.Policy)
.IsRequired(false)
.HasForeignKey<PayPlan>(b => b.PolicyId)
.OnDelete(DeleteBehavior.Cascade);
}
This will produce the following tables on SQL:
I hit an issue when trying to delete records due to FK constraints. I therefore went back to the drawing board and am trying to specify how the relationship should work.
Here are my code first classes:
public class MemberDataSet
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? DeferredDataId { get; set; }
[ForeignKey("DeferredDataId")]
public virtual DeferredData DeferredData { get; set; }
}
public class DeferredData
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
//other properties
}
What I am looking to achieve is that the MemberDataSet has zero or one DeferredData. I can access DeferredData from MemberDataSet but DeferredData does not need a navigation property back to MemberDataSet. DeferredData should strictly require a MemberDataSet. In an ideal world deleting MemberDataSet will therefore delete DeferredData if assigned.
What seemed to me to be what I wanted to specify is this:
modelBuilder.Entity<MemberDataSet>().HasOptional(d => d.DeferredData).WithRequired().WillCascadeOnDelete(true);
i.e. MemberDataSet has an option DeferredData but DeferredData has a required MemberDataSet and this relationship should cascade on delete.
However, I then get an error:
The ForeignKeyAttribute on property 'DeferredData' on type 'MemberDataSet' is not valid. The foreign key name 'DeferredDataId' was not found on the dependent type 'DeferredData'. The Name value should be a comma separated list of foreign key property names.
Edit
After feeling happy with Sam's answer below I went ahead and changed a few other ForeignKey attributes. MemberDataSet has another property called SignedOffBy that is a userProfile. This previously looked like this:
public class MemberDataSet
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? DeferredDataId { get; set; }
[ForeignKey("DeferredDataId")]
public virtual DeferredData DeferredData { get; set; }
public int? SignedOffById { get; set; }
[ForeignKey("SignedOffId")]
public virtual UserProfile SignedOffBy { get; set; }
}
After discussion below on what ForeignKey attribute is actually doing I changed this to:
public class MemberDataSet
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? DeferredDataId { get; set; }
[ForeignKey("Id")]
public virtual DeferredData DeferredData { get; set; }
public int? SignedOffById { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile SignedOffBy { get; set; }
}
However, I now get a very similar error message:
The ForeignKeyAttribute on property 'SignedOffBy' on type 'MemberDataSet' is not valid. The foreign key name 'UserId' was not found on the dependent type 'MemberDataSet'. The Name value should be a comma separated list of foreign key property names.
The difference here is that this relationship is Many to One i.e. 1 user can have several signedoff datasets. Is this what makes the difference? i.e. the UserProfile is now the principal object so the ForeignKey is on the MemberDataSet?
Many thanks again for any and all help.
The error
The ForeignKeyAttribute on property 'DeferredData' on type
'MemberDataSet' is not valid. The foreign key name 'DeferredDataId'
was not found on the dependent type 'DeferredData'.
is telling you exactly what is wrong.
DeferredData.Id is not DeferredData.DeferredDataId
This is your problem.
Just removing the attribute will solve your problem as Entity Framework figures out foreign keys based on the name of your entities. If you want to keep the attributes, use:
[ForeignKey("Id")]
instead of
[ForeignKey("DeferredDataId")]
So:
public class MemberDataSet
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? DeferredDataId { get; set; }
[ForeignKey("Id")]
public virtual DeferredData DeferredData { get; set; }
}
or change the Id of DeferredData to be DeferredDataId and not Id
A few notes about EF:
Properties with names Id are automatically Keys, so no need for the Key attribute
When you define a relationship using code first you don't need to manually decorate things with attributes, EF figures it out based on the structure.
Edit:
For a One-to-many relationship you need an ICollection<T>
public virtual ICollection<MemberDataSet> MemberDataSets { get; set; }
Does UserProfile have a UserId property?
I am trying to do code first with annotations (for the first time) on an MVC project.
I have created the following POCOs.
[Table("Customers")]
public partial class Customer
{
public int Id { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
//other properties...
}
[Table("Vehicles")]
public partial class Vehicle
{
[Required]
public int Id { get; set; }
[Required]
public int CustomerId { get; set; }
[Required]
public string Make { get; set; }
[Required]
public string Model { get; set; }
[Required]
public string Year { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
[Table("CustomerAppointments")]
public partial class CustomerAppointment
{
[Key,Column(Order=0)]
public int CustomerId { get; set; }
[Key,Column(Order=1)]
public int VehicleId { get; set; }
public DateTime? AppointmentDate { get; set; }
public DateTime? AppointmentTime { get; set; }
public string AvailableDays { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
[ForeignKey("VehicleId")]
public virtual Vehicle Vehicle { get; set; }
}
I think my intent here is fairly obvious. I have customers. Those customers have vehicles. I want to create a table CustomerAppointments where a customer and one of the customers vehicles is scheduled for a service.
For the record, this is not the whole model and has been simplified for the purposes of the question.
I am using MvcScaffolding to build out the EF items and the views.
Everything compiles but when I try to navigate to the Customers page (actually a class not mentioned that references customers) I am getting the following error...
Introducing FOREIGN KEY constraint 'FK_dbo.CustomerAppointments_dbo.Vehicles_VehicleId' on table 'CustomerAppointments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I have tried different annotations and even tried to use the fluent API with something like this...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Customer)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Vehicle)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
}
But I cannot get it to work. I have read every sample I can find on google and SO but to no avail.
PS...if this can work with Annotations only that would be my preference.
Your model has two cascading delete paths from Customer to CustomerAppointment when a Customer is deleted:
Customer -> Vehicle -> CustomerAppointment
Customer -> CustomerAppointment
That's not allowed in SQL Server and causes the exception. You need to disable cascading delete for at least one of those three subpaths which is only possible with Fluent API. For example the Customer -> Vehicle path:
modelBuilder.Entity<Vehicle>()
.HasRequired(v => v.Customer)
.WithMany()
.HasForeignKey(v => v.CustomerId)
.WillCascadeOnDelete(false);
You could also make CustomerId nullable to have an optional relationship in which case EF will disable cascading delete by default. But changing a required to an optional relationship expresses a change in business rules which I wouldn't do just to avoid Fluent API.
BTW: Is it really correct that CustomerAppointment should have a composite primary key? It would mean that a given customer with a given vehicle could only have one service appointment. Couldn't there be many appointments for the same customer/vehicle combination at different appointment dates? If yes, you should rather have a separate key for CustomerAppointment and CustomerId and VehicleId would be just foreign keys without being part of the primary key.
It seems like you are better off using the database-first approach and then generating the model using ado enity data model.
By convention, cascade deletes are handled by the introduction of the actual foreign key into your model. If you use a non-nullable foreign key, it will require delete. Use a nullable foreign key to turn it off.
Change your class to the following by making the foreign keys nullable:
[Table("CustomerAppointments")]
public partial class CustomerAppointment
{
[Key,Column(Order=0)]
public int? CustomerId { get; set; }
[Key,Column(Order=1)]
public int? VehicleId { get; set; }
public DateTime? AppointmentDate { get; set; }
public DateTime? AppointmentTime { get; set; }
public string AvailableDays { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
[ForeignKey("VehicleId")]
public virtual Vehicle Vehicle { get; set; }
}
Remember to also remove the fluent mapping.
From http://msdn.microsoft.com/en-US/data/jj679962
If a foreign key on the dependent entity is not nullable, then Code
First sets cascade delete on the relationship. If a foreign key on the
dependent entity is nullable, Code First does not set cascade delete
on the relationship, and when the principal is deleted the foreign key
will be set to null.
I have three model classes:
User.
Entry.
EntryLikes.
As follows:
public class User
{
[Required]
public int ID { get; set; }
[Required]
[DataType(DataType.Text)]
public string Name { get; set; }
}
public class Entry
{
[Required]
public int ID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
public class EntryLike
{
[Required]
public int ID { get; set; }
[Required]
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
[Required]
public int EntityID { get; set; }
[ForeignKey("EntityID")]
public virtual Entry Entry { get; set; }
}
Upon execution I got following exception:
Introducing FOREIGN KEY constraint
'FK_dbo.EntryLikes_dbo.Entries_EntityID' on table 'EntryLikes' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could
not create constraint. See previous errors.
Why do you have a foreign key relationship with User from EntryLike and from Entry? Given that you have a relationship between Entry and User on the Entry class, you don't need one on the EntryLike class as it can be inferred due to the relationship between EntryLike and Entry. Also, should the foreign key id property on EntryLike be called EntryID rather than EntityID?
EDIT: It's because you have multiple cascade paths to your User - one is Entry > User and the other is EntryLike > Entry > User. You will need to switch cascade delete off to stop this error from occurring. The links I put in the comment should get you on the right track.
You must disable cascading delete for at least one of the relationships EntryLike is involved in. Cascading delete is turned on by default for every required one-to-many relationship. You need Fluent API for this, it's not possible with data annotations. For example:
modelBuilder.Entity<EntryLike>()
.HasRequired(el => el.Entry)
.WithMany()
.HasForeignKey(el => el.EntryID)
.WillCascadeOnDelete(false);