Introducing FOREIGN KEY constraint 'FK_Product_User_UserId' on table 'Product' may cause cycles or multiple cascade paths - .net-core

i cannot create database with ef core
error : Introducing FOREIGN KEY constraint 'FK_Product_User_UserId' on table 'Product' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
this is my product class
{
public Product()
{
}
public Guid UserId { get; set; }
public Guid CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string PhotoPath { get; set; }
public decimal Price { get; set; }
public Category Category { get; set; }
public User User { get; set; }
}
and
this is my user class
{
public User()
{
Payments = new HashSet<Payment>();
Categories = new HashSet<Category>();
Products = new HashSet<Product>();
}
public string Username { get; set; }
public Guid Password { get; set; }
public ICollection<Payment> Payments { get; set; }
public ICollection<Category> Categories { get; set; }
public ICollection<Product> Products { get; set; }
}
its mapping class
{
public ProductMap()
{
}
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.HasKey(x => x.Id);
builder.Property(x => x.UserId).IsRequired();
builder.Property(x => x.CreatedDate).IsRequired();
builder.Property(x => x.Description).HasMaxLength(500);
builder.Property(x => x.IsActive).IsRequired();
builder.Property(x => x.Name).HasMaxLength(500).IsRequired();
builder.Property(x => x.PhotoPath).HasMaxLength(4000);
builder.Property(x => x.Price).HasColumnType("decimal(10,3)").IsRequired();
builder.HasOne(x => x.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
builder.HasOne(x => x.User).WithMany(x => x.Products).HasForeignKey(x => x.UserId);
}
}
and i cannot create database cause error like this posts title.
what can i do?
Thanks.

You are saying that each user has many Categories and each Category has many Products so you have to remove this line from the User class since it causing cycle path
public ICollection<Product> Products { get; set; }
And also fix the last line of the Configure method:
builder.HasOne(x => x.User).WithMany(x => x.Categories).HasForeignKey(x => x.UserId);

Related

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId"

I successfully built migrations, and I am now trying to update the database with my models in Asp.net core but it keeps giving me this error
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId". The conflict occurred in database "MediumDb", table "dbo.Authors", column 'AuthorId'.
The statement has been terminated."
This is what the code in my Post class looks like
namespace Medium.Api.Entities
{
public class Post
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int NoOfClaps { get; set; }
public DateTime CreatedDate { get; set; }
public IQueryable<Tag> Tags { get; set; }
public IQueryable<PostTag> PostTags { get; set; }
public string Image { get; set; }
// public string Video { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
while the code in my Author class says this
namespace Medium.Api.Entities
{
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public IQueryable<Post> Posts { get; set; }
}
}
This is my DbContext configuration
{
public class MediumApiContext : DbContext
{
public MediumApiContext(DbContextOptions options)
: base(options)
{
// Database.EnsureCreated();
}
public DbSet<Post> Posts { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>()
.HasKey(a => a.AuthorId);
modelBuilder.Entity<Author>()
.HasMany(a => a.Posts)
.WithOne(p => p.Author);
modelBuilder.Entity<Post>()
.ToTable("Posts");
modelBuilder.Entity<Post>()
.HasKey(p => p.Id);
modelBuilder.Entity<Post>()
.HasOne(p => p.Author)
.WithMany(a => a.Posts);
modelBuilder.Entity<Post>()
.Property(p => p.CreatedDate)
.IsRequired()
.HasColumnType("Date")
.HasDefaultValueSql("getutcdate()");
modelBuilder.Entity<Post>()
.Property(p => p.Title)
.IsRequired();
modelBuilder.Entity<Post>()
.Property(p => p.NoOfClaps)
.IsRequired();
modelBuilder.Entity<Post>()
.Property(p => p.Content)
.IsRequired();
I don't know where I seem to be getting it all wrong. Please
We Use FK for data integrity right now you have FOREIGN KEY with Author Table so :
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId". The conflict occurred in database "MediumDb", table "dbo.Authors", column 'AuthorId'. The statement has been terminated."
This means that when you create a Post, you must give an Author_ID that is on the Author table

Introducing FOREIGN KEY constraint with ON DELETE NO ACTION doesn't working

I have 4 tables with between them foreign keys as:
Classification - Classification level - Classification value - Classification language
on add-migration it is ok, but when running update-database I get the error:
Introducing FOREIGN KEY constraint 'FK_dbClassificationValue_dbClassificationLevel_ClassificationLevelId' on table 'dbClassificationValue' 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.
The tables as mentioned in the error are defined as:
public class SuClassificationLevelModel
{
public int Id { get; set; }
public int ClassificationId { get; set; }
public int Sequence { get; set; }
public bool DateLevel { get; set; }
public bool OnTheFly { get; set; }
public bool Alphabetically { get; set; }
public bool CanLink { get; set; }
public bool InDropDown { get; set; }
public Guid CreatorId { get; set; }
public Guid ModifierId { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime CreatedDate { get; set; }
public virtual SuClassificationModel Classification { get; set; }
public virtual ICollection<SuClassificationLevelLanguageModel> ClassificationLevelLanguages { get; set; }
public virtual ICollection<SuClassificationValueModel> ClassificationValues { get; set; }
}
and
public class SuClassificationValueModel
{
public int Id { get; set; }
public int ClassificationLevelId { get; set; }
public int ParentValueId { get; set; }
public DateTimeOffset DateFrom { get; set; }
public DateTimeOffset DateTo { get; set; }
public virtual SuClassificationLevelModel ClassificationLevel { get; set; }
public virtual ICollection<SuClassificationValueLanguageModel> ClassificationValueLanguages { get; set; }
}
I have added the delete behavior line in my DBContect class as:
modelBuilder.Entity<SuClassificationValueModel>()
.HasOne(u => u.ClassificationLevel)
.WithMany(u => u.ClassificationValues)
.HasForeignKey(u => u.ClassificationLevelId)
.OnDelete(DeleteBehavior.Restrict);
Also, I have put this on the foreign keys between all tables of the cascading structure.
modelBuilder.Entity<SuClassificationLevelModel>()
.HasOne(u => u.Classification)
.WithMany(u => u.ClassificationLevels)
.HasForeignKey(u => u.ClassificationId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<SuClassificationValueModel>()
.HasOne(u => u.ClassificationLevel)
.WithMany(u => u.ClassificationValues)
.HasForeignKey(u => u.ClassificationLevelId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<SuClassificationValueLanguageModel>()
.HasOne(u => u.ClassificationValue)
.WithMany(u => u.ClassificationValueLanguages)
.HasForeignKey(u => u.ClassificationValueId)
.OnDelete(DeleteBehavior.Restrict);
Further, I have tried to set it for all foreign keys with:
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
As I don't need the cascading delete behavior.
After these different tries I did again an add-migration and update-database. But the error is still the same.
Any suggestions?
Finally, I went into the migration files and changed everywhere from cascade to restrict. As I don't want to use cascade anyway. And now it works.

How to define two FK in the same table?

I have a table called User which inherit the properties from IdentityUser, inside that table I added a reference to the UserFriendship table which need to store all the user friendship:
public class User : IdentityUser
{
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public virtual ICollection<UserFriendship> UserFriendship { get; set; }
}
Essentially the UserFriendship contains two users, who are those who have a common friendship, this is the model definition:
public class UserFriendship
{
public int Id { get; set; }
[Key, ForeignKey("UserA")]
public string UserAId { get; set; }
public User UserA { get; set; }
[Key, ForeignKey("UserB")]
public string UserBId { get; set; }
public User UserB { get; set; }
[Required]
public DateTime DateTime { get; set; }
}
I defined the UserA and the UserB which are two FK of a User that are contained inside AspNetUsers table.
Now inside the FluentAPI I declared the following:
builder.Entity<UserFriendship>(entity =>
{
entity.HasKey(f => f.Id);
entity.HasOne(u => u.UserA)
.WithMany(n => n.UserFriendships)
.HasForeignKey(u => u.UserAId)
.IsRequired();
entity.HasOne(u => u.UserB)
.WithMany(n => n.UserFriendships)
.HasForeignKey(u => u.UserBId)
.IsRequired();
});
when I execute this command:
add-migration InitialMigration -context MyAppContext
I'll get:
Cannot create a relationship between 'User.UserFriendships' and 'UserFriendship.UserB', because there already is a relationship between 'User.UserFriendships' and 'UserFriendship.UserA'. Navigation properties can only participate in a single relationship.
I'm not an expert of EnityFramework, but based on that error I think that I cannot define two FK in the same table?
Sorry for any mistake, thanks.
You can define more than one FK in table.
The problem here is you are pointing two times to one navigation property - UserFriendships. The solution would be to create two navigation properties.
Navigation properties are used to browse the related data for specified foreign-key (you have one-to-many relationship) of entity.
Try this:
public class User
{
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public ICollection<UserFriendship> UserAFriendships { get; set; }
public ICollection<UserFriendship> UserBFriendships { get; set; }
}
public class UserFriendship
{
public int Id { get; set; }
public string UserAId { get; set; }
public User UserA { get; set; }
public string UserBId { get; set; }
public User UserB { get; set; }
public DateTime DateTime { get; set; }
}
And define the relationship through fluent api as following:
modelBuilder.Entity<UserFriendship>(entity =>
{
entity.HasKey(f => f.Id);
entity.HasOne(u => u.UserA)
.WithMany(n => n.UserAFriendships)
.HasForeignKey(u => u.UserAId)
.IsRequired();
entity.HasOne(u => u.UserB)
.WithMany(n => n.UserBFriendships)
.HasForeignKey(u => u.UserBId)
.IsRequired();
});
What is more - you don't need to specify attributes Key, ForeignKey if you use Fluent API.

How can i access related data and convert foreign keys into objects for displaying their properties

I have
class User {
...
...
ICollection<Transaction> transactionsUserMade;
}
and
class Transaction {
int ID;
int userThatSentMoneyID;
int userToWhomHeSentMoneyID;
}
I'm trying to make profile page where user can see all transactions he made and to whom. I managed to relate users and transaction but I'm getting integer values, as i should by using
await _context.Users
.Include(u => u.transactionsUserMade)
.AsNoTracking()
.FirstOrDefaultAsync(u => u.ID == userId);
How can i turn those ID's to actual objects of Users so i could get their usernames and display them on Razor Page.
Found one solution. I tweaked Transaction class by adding User userThatRecievedMoney property. And after getting transactions from specific user i manually set that property.
foreach(var transaction in _user.transactionsUserMade)
{
transaction.userThatRecievedMoney = _context.Users
.Where(u => u.ID == transaction.userToWhomHeSentMoneyID).FirstOrDefault();
}
You can use Navigation Property to help you with that as long as you can modify those entity models User and Transaction.
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<TransactionEntity> TransactionsAsSender { get; set; }
public List<TransactionEntity> TransactionsAsRecipient { get; set; }
}
public class TransactionEntity
{
public int Id { get; set; }
public double Amount { get; set; }
public string Note { get; set; }
// Foreign key to UserEntity
public int SenderId { get; set; }
public UserEntity Sender { get; set; }
// Foreign key to UserEntity
public int RecipientId { get; set; }
public UserEntity Recipient { get; set; }
}
Then you need to setup their relationships.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserEntity>(b => {
b.HasKey(x => x.Id);
b.Property(x => x.Name).IsRequired();
b.Property(x => x.Email).IsRequired();
b.ToTable("User");
});
builder.Entity<TransactionEntity>(b => {
b.HasKey(x => x.Id);
b.Property(x => x.Amount).IsRequired();
// Configure relationships
b.HasOne(x => x.Sender)
.WithMany(u => u.TransactionsAsSender)
.HasForeignKey(x => x.SenderId);
b.HasOne(x => x.Recipient)
.WithMany(u => u.TransactionsAsRecipient)
.HasForeignKey(x => x.RecipientId);
b.ToTable("Transaction");
});
}
public DbSet<UserEntity> Users { get; set; }
public DbSet<TransactionEntity> Transactions { get; set; }
}
After their relationships are setup, you can easily query the related data via navigation properties.
For example, let's say you have view model called UserProfileViewModel and UserProfileTransactionViewModel to contain the information it needs for display purpose.
public class UserProfileViewModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
public IEnumerable<UserProfileTransactionViewModel> TransactionsAsSender { get; set; }
public IEnumerable<UserProfileTransactionViewModel> TransactionsAsRecipient { get; set }
}
public class UserProfileTransactionViewModel
{
public int TransactionId { get; set; }
public string Sender { get; set; }
public string Recipient { get; set; }
public string Amount { get; set; }
}
In the controller,
var user = _dbContext.Users
.AsNoTracking()
.Include(x => x.TransactionsAsSender)
.Include(x => x.TransactionsAsRecipient)
.SingleOrDefault(x => x.Id == userId);
if (user == null)
{
return NotFound();
}
var vm = new UserProfileViewModel
{
UserId = user.Id,
UserName = user.Name,
UserEmail = user.Email,
TransactionsAsSender = user.TransactionsAsSender
.Select(x => new UserProfileTransactionViewModel
{
TransactionId = x.Id,
Sender = x.Sender.Name,
Recipient = x.Recipient.Name,
Amount = x.Amount.ToString("c")
}),
TransactionsAsRecipient = user.TransactionsAsRecipient
.Select(x => new UserProfileTransactionViewModel
{
TransactionId = x.Id,
Sender = x.Sender.Name,
Recipient = x.Recipient.Name,
Amount = x.Amount.ToString("c")
})
};
return View(vm);
You could even have just a list of all transactions off UserProfileViewModel. You can combine TransactionsAsSender and TransactionsAsRecipient from UserEntity to fill the list.
Disclaim:
I wrote everything by hand and with my imagination :p

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

I am getting these errors when trying to create a merchant.
FlavorPing.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
FlavorPing.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
UserLogins: EntityType: EntitySet 'UserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
UserRoles: EntityType: EntitySet 'UserRoles' is based on type 'IdentityUserRole' that has no keys defined."
Here is my merchant model:
namespace FlavorPing.Models
{
public class Merchant
{
//Meant to inherit identity.
//[ForeignKey("ApplicationUserId")]
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUser")]
public virtual List<ApplicationUser> ApplicationUser { get; set; }
[Key]
public int MerchantID { get; set; }
[Required]
[Display(Name = "Business Name")]
public string MerchantName { get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string email { get; set; }
//need to create formatting here.
[Required]
[Display(Name = "Web Site Link")]
public string website { get; set; }
//public int MenuItemID { get; set; }
public virtual List<MenuItem> MenuItems { get; set; }
public virtual MerchantDetails MerchantDetails { get; set; }
public ICollection<FollowerMenuItemMerchant> FollowerMenuItemMerchants { get; set; }
}
}
Here is the create controller for merchant, which is where I am getting the error:
// POST: Merchants/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "MerchantID,MerchantName,email,website")] Merchant merchant)
{
if (ModelState.IsValid)
{
merchant.ApplicationUserId = User.Identity.GetUserId();
db.Merchants.Add(merchant);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(merchant);
}
Here is my DBContext:
namespace FlavorPing.Models
{
public class FlavorPingContext : IdentityDbContext
{
public FlavorPingContext()
: base("name=FlavorPingContext")
{
}
public System.Data.Entity.DbSet<FlavorPing.Models.Merchant> Merchants { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.MenuItem> MenuItems { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.MerchantDetails> MerchantDetails { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.Follower> Followers { get; set; }
public System.Data.Entity.DbSet<FlavorPing.Models.FollowerMenuItemMerchant> FollowerMenuItemMerchants { get; set; }
public DbSet<IdentityUserLogin> UserLogins { get; set; }
public DbSet<IdentityUserClaim> UserClaims { get; set; }
public DbSet<IdentityUserRole> UserRoles { get; set; }
protected override void OnModelCreating(DbModelBuilder builder)
{
// Primary keys
builder.Entity<Follower>().HasKey(q => q.FollowerID);
builder.Entity<MenuItem>().HasKey(q => q.MenuItemID);
builder.Entity<Merchant>().HasKey(q => q.MerchantID);
builder.Entity<FollowerMenuItemMerchant>().HasKey(q =>
new
{
q.FollowerID,
q.MenuItemID,
q.MerchantID
});
// Relationships
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.Follower)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.FollowerID);
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.MenuItem)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.MenuItemID);
builder.Entity<FollowerMenuItemMerchant>()
.HasRequired(t => t.Merchant)
.WithMany(t => t.FollowerMenuItemMerchants)
.HasForeignKey(t => t.MerchantID);
builder.Conventions.Remove<PluralizingTableNameConvention>();
builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
}
I am trying to follow the example (option2) in this link: EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType
I am trying Option 2 because I want to avoid having two DB's. But I am new to managing a DB so if you think I should do Option 3 please advise as to why, or if you see why I am getting this error please tell me why. Thanks in advance!
Ok I fixed my issue by adding this into my DBContext class.
builder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
builder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
builder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
I think you get the errors because your foreign key attributes aren't in the correct spot (and have the wrong name), instead of this:
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUser")]
public virtual List<ApplicationUser> ApplicationUser { get; set; }
You need to do this:
[ForeignKey("ApplicationUser")]
public string ApplicationUserId { get; set; }
public virtual List<ApplicationUser> ApplicationUser { get; set; }
The ID is the foreign key to the virtual entity, not the other way around.

Resources