Code First cascade issue - c#

this is the error I'm getting:
"Introducing FOREIGN KEY constraint FK_dbo.RolePermissions_dbo.Permissions_Permission_ID on table RolePermissions 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 or index. See previous errors."
and here are my classes:
public class Permission
{
[Key]
public int ID { get; set; }
[Required]
public int PermissionObjectId { get; set; }
public PermissionObject PermissionObject { get; set; }
[Required]
public int CategoryId { get; set; }
public Category Category { get; set; }
[Required]
public int ReadWriteId { get; set; }
public ReadWrite ReadWrite { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
[Key]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CategoryId { get; set; }
public Category Category { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
}
public class Category
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int OrderID { get; set; }
public override string ToString()
{
return ID.ToString();
}
}
what do I do wrong?

use fluent api for set CascadeOndelete = fasle .
See This Link May Be Help you : Link

It looks like EF is trying to create a relationship of some sort between Roles and Permissions (many-to-many?), but you also have one-to-many relationships for category-role and category-permission which also have cascade delete enabled.
For foreign key relationships when using non-nullable keys or [Required], (e.g. CategoryId in both Role and Permission), cascade delete is enabled by default.

Related

Create navigation property without foreign key

I have two classes like so:
[Table("GameLevels", Schema = "ref")]
public class GameLevel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public double PointsMin { get; set; }
public double PointsMax { get; set; }
}
[Table("GameProfiles", Schema = "usr")]
public class UserGameProfile
{
[Key]
[ForeignKey("ApplicationUser")]
public string Id { get; set; }
public int GamesPlayed { get; set; }
public double Points { get; set; }
public int WinCount { get; set; }
public int LossCount { get; set; }
public int DrawCount { get; set; }
public int ForfeitCount { get; set; }
public int GameLevelId { get; set; }
public virtual GameLevel Level { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Entity framework builds this so that UserGameProfile has a foreign key pointing to GameLevel. I guess this is because of the GameLevelId property.
Is there any way I can get this to generate the tables and navigation property without the foreign key?
I tried:
modelBuilder.Entity<UserGameProfile>().HasOptional<GameLevel>(x => x.Level).WithMany();
But then database fails to build. With this error:
One or more validation errors were detected during model generation:
Project.Domain.Data.UserGameProfile_Level: : Multiplicity
conflicts with the referential constraint in Role
'UserGameProfile_Level_Target' in relationship
'UserGameProfile_Level'. Because all of the properties in the
Dependent Role are non-nullable, multiplicity of the Principal Role
must be '1'.
Basically what I want is a zero-or-one to zero-or-many relationship.
How do I keep levels independent but have the ability to add a level to a profile?
You can't drop the foreign key completely, otherwise, how do you expect the two entities (i.e, tables) to be linked? What you can do instead is have a nullable FK, which will effectively make the relationship zero-or-one to many.
In your GameLevel class, add a navigation property as a collection of UserGameProfile:
public class GameLevel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public double PointsMin { get; set; }
public double PointsMax { get; set; }
public virtual ICollection<UserGameProfile> UserGameProfiles { get; set; }
}
Then in the UserGameProfile class, make the property GameLevelId nullable:
public class UserGameProfile
{
// ...
// ...
public int? GameLevelId { get; set; }
[ForeignKey("GameLevelId")]
public virtual GameLevel GameLevel { get; set; }
}
This should work without even having to use Fluent API.

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.

How to define a table that its primary key is constructed from 2 foreign keys with EF code-first

I am using models to define my tables using EF code-first.
I have and Item model and an Order model.
Item:
public class Item
{
public int ItemID { get; set; }
[Required]
public int Price { get; set; }
[Required]
public int AmountLeft { get; set; }
[Required]
public string Image { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string FullDescription { get; set; }
[Required]
public DateTime PublishDate { get; set; }
public int CompanyID { get; set; }
public int CategoryID { get; set; }
// Navigation properties
public virtual Company Company { get; set; }
// Navigation properties
public virtual Category Category { get; set; }
}
Order model:
public class Order
{
public int OrderID { get; set; }
[Required]
public DateTime DeliveryDate { get; set; }
[Required]
public string Currency { get; set; }
[Required]
public int TotalAmount { get; set; }
public List<int> Items { get; set; }
public DateTime OrderDate { get; set; }
public int UserID { get; set; }
// Navigation properties
public virtual User user { get; set; }
}
I want to create another table which will be called ItemInOrder which will only have 2 fields: ItemID and OrderID.
the primary key would be these 2 foreign keys.
i tried to define this model:
public class ItemInOrder
{
public int OrderID { get; set; }
public int ItemID { get; set; }
// Navigation properties
public virtual Order order { get; set; }
public virtual Item item { get; set; }
}
But i got errors. i tried to put [Key] notation on both fields but still i got errors.
how will i be able to create the table i want?
When you need to create a table with composite PKs, you need to specify the order of you keys. There are two variants:
You could override the OnModelCreating method on your Context, and try with these Fluent Api configurations:
// Configure the primary keys for the ItemInOrder in the order you want
modelBuilder.Entity<ItemInOrder>()
.HasKey(t => new{t.OrderID,ItemID);
modelBuilder.Entity<ItemInOrder>()
.HasRequired(io=>io.Order)
.WithMany()
.HasForeigKey(io=>io.OrderID);
modelBuilder.Entity<ItemInOrder>()
.HasRequired(io=>io.Item)
.WithMany()
.HasForeigKey(io=>io.ItemID);
The second variant using Data Annotations should be this way:
[Key]
[Column(Order=1)]
[ForeignKey("Order")]
public int OrderID { get; set; }
[Key]
[Column(Order=2)]
[ForeignKey("Item")]
public int ItemID { get; set; }
EF will notice you want to create two relationships and it will do the job for you.

Setting up foreign key in ASP.NET MVC 4

I have 2 models and want to create a foreign key relationship. Basically each note should be assigned to a user.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
[Table("UserNotes")]
public class UserNotes
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int NoteId { get; set; }
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Added { get; set; }
public DateTime? Edited { get; set; }
}
When I attempt to add new user note I get:
The ForeignKeyAttribute on property 'UserId' on type 'note.DO.Models.UserNotes' is not valid. The navigation property 'UserProfile' was not found on the dependent type 'note.DO.Models.UserNotes'. The Name value should be a valid navigation property name.
I have tried a lot of combinations including those found in similar questions but none of them worked.
Try this :
public virtual int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }
This way, you pair foreign key property with navigation property.
Edit : you can also write it like this :
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
Those two snippets gives the same result. Your error message says that "UserProfile" property is missing, you just have to add it.

Creating relationships in entity with out foreign keys

I am using the code first approach, to create the database based on modals and the db context class. The problem is that when I create the relationships between one model and the next and run the code the data base generates foreign keys like it should.
How ever I want the relationships, with out the foreign keys. is this possible to do with entity framework and the code first approach?
for example:
namespace LocApp.Models
{
public class Location
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
public string address { get; set; }
[Required]
public string city { get; set; }
[Required]
public string country { get; set; }
[Required]
public string province { get; set; }
[Required]
public string phone { get; set; }
public string fax { get; set; }
public bool active { get; set; }
public virtual ICollection<LocationAssignment> LocationAssignment { get; set; }
}
}
Has a relationship with:
namespace LocApp.Models
{
public class LocationAssignment
{
public int id { get; set; }
public int locationID { get; set; }
public int serviceID { get; set; }
public int productID { get; set; }
public int personID { get; set; }
public virtual Location Location { get; set; }
public virtual Service Service { get; set; }
public virtual Product product { get; set; }
public virtual Person person { get; set; }
}
}
As you can see this table will have a foreign key generated with the location table. How do I keep this relationship WITH OUT the generation of foreign keys?
User Triggers On Insert and on update and delete relative and reference tables !!! but that's not cute you must control allthing in your application instead

Categories