I'm just ramping up on MVC 4 and have encountered an error in my application that I need some assistance in fixing.
I have an Author & Book table. The Author table is the parent, and you can have multiple Books associated with each author.
Everything is working well until I try to delete an Author that still has Books assigned to him. When that happens, I receive an error at SaveChanges() stating:
The DELETE statement conflicted with the REFERENCE constraint
"FK_Book_Author".
The error makes perfect sense, but I would like the application to give a nice error message to the users rather than simply exploding.
How do I go about defining this relationship in the model so it doesn't cause the application to explode when you delete a record with children associated to it?
Author Class
public partial class Author
{
public Author()
{
this.Book = new HashSet<Book>();
}
[Key]
public int AuthorId { get; set; }
[Required]
public string AuthorName { get; set; }
public virtual Book Book { get; set; }
}
Book Class
public partial class Book
{
[Key]
public int BookId { get; set; }
[Required]
public string BookName { get; set; }
[Required]
[ForeignKey("Author")]
public string AuthorId { get; set; }
}
Model
I have recently started attempting to override OnModelCreating, but it appears to have no affect.
public partial class BookEntities : DbContext
{
public BookEntities()
: base("name=BookEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>().HasRequired(p => p.Author)
.WithMany(b => b.Books)
.HasForeignKey(p => p.AuthorId);
modelBuilder.Entity<Author>()
.HasMany(p => p.Books)
.WithRequired(b => b.Author)
.WillCascadeOnDelete(false);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}
Partial Updates
This is an issue regarding 0..1-To-Many relationships
I am using an .edmx. I've just learned that this negates the OnModelCreating method completely.
It appears that I can throw a Linq statement into the DeleteConfirmed method to block this from crashing, but I really do not like that approach.
I generally do not use the attributes if I am also using the fluent API, so this code will be entirely convention and fluent API.
Your post does not specify, but the classic book=>authors model is a many to many relationship. Your Entity code seems to be saying that there is exactly one author and exactly one book, while your fluent code seems to be implying that there are collections of Books and Authors.
FWIW, here is what I would Have:
public class Author
{
public int AuthorId { get; set; }
public string AuthorName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string BookName { get; set; }
public virtual ICollection<Author> Authors { get; set; }
}
and in the Override:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>()
.HasMany(a => a.Books)
.WithMany(b => b.Authors)
.Map(m =>
{
m.ToTable("AuthorBooks");
m.MapLeftKey("AuthorId");
m.MapRightKey("BookId");
});
}
This will yield the db of:
I believe that is all you would need to get the cascade, by convention it should perform the cascade.
Please post if this is not what you were looking for.
Tal
Solution
After spending a day struggling on this one issue, I decided to put some custom code into the DeleteConfirmed method to prevent the error from arising & to alert the user that this record could not be removed.
This is probably not the best way to handle the situation, but it is functional.
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Author author = db.Authors.Find(id);
// Count # of Books for this Author
int count = (from book in db.Books
where book.BookId == id
select book.BookId).Count();
// Prevent deletion of this record has any associated records
if (count> 0)
{
TempData["errors"] = "Bad user! You can't delete this record yet!";
return RedirectToAction("Delete");
}
else
{
db.Categories.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
}
Related
I am making a web app similar to google classroom in that you can join classes.
I have a class "Account" and inside that account I have a list that should hold the IDs of all the classes the account has joined. I tried to make the list a list of longs, but I couldn't do that because I got the error:
System.InvalidOperationException: 'The property
'Account._classesJoined' could not be mapped, because it is of type
'List' which is not a supported primitive type or a valid entity
type. Either explicitly map this property, or ignore it using the
'[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
'OnModelCreating'.
The way I solved this problem is to create a class "JoinedClassId" to make a list of instead, with a property "classIdNumber". However, during testing, I noticed that the JoinedClassIds that I added to the the Account object were not saving. I think this is because I am not saving the database table for the JoinedClassId class.
Do I have to create a database context and controller for the JoinedClassId class? I don't want to be able to manipulate the JoinedClassId class from the API, I'm only using it as a data container. Is there a way I could either create a long list and save it or save the JoinedClassIds?
In EF Core "Many-to-many relationships without an entity class to represent the join table are not yet supported".
Book -> Category has many-to-may rel so this should create the 3 tables in DB :
Books, Category and BookCategory
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
//public ICollection<Category> Categories { get; set; } // cannot appear
// For the many-to-many rel
public List<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
//public ICollection<Book> Books { get; set; } // cannot appear
// For the many-to-many rel
public List<BookCategory> BookCategories { get; set; }
}
// Class because of the many-to-many rel
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class MyContextDbContext : DbContext
{
public MyContextDbContext(DbContextOptions<MyContextDbContext> dbContextOptions)
: base(dbContextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BookCategory>()
.HasKey(t => new { t.BookId, t.CategoryId });
modelBuilder.Entity<BookCategory>()
.HasOne(bctg => bctg.Book)
.WithMany(ctg => ctg.BookCategories)
.HasForeignKey(book => book.CategoryId);
modelBuilder.Entity<BookCategory>()
.HasOne(bctg => bctg.Category)
.WithMany(ctg => ctg.BookCategories)
.HasForeignKey(ctg => ctg.BookId);
}
public DbSet<Book> Book { get; set; }
public DbSet<Category> Category { get; set; }
}
How do you make EF not allow deletion of a related entity? eg:
public class Enrollment
{
public int EnrollmentId { get; set; }
public virtual ICollection<Course> courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
}
When I create a Course A and B, and then I create an Enrollment and add those courses to it, I need it to not allow me to delete Courses A or B. When I run it through my MVC controller this has no problem:
Course course = db.Courses.Find(id);
db.Courses.Remove(course);
db.SaveChanges();
I'm not even sure exactly what to search for. I think it's enforcing or enabling a many to many referential constraint? But I don't seem to find anything. Am I supposed to not expect it to make that constraint automatically? I figured I could always add the following line to the Delete controller:
if(db.Enrollments.Any(e => e.Courses.Any(c => c.CourseId == id)))
{ //error }
Also, trying the following fluentAPI wasn't working (among many variations):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Enrollment>()
.HasMany<Course>(e => e.Courses)
.WithRequired()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Course>()
.HasMany(e => e.Enrollments);
base.OnModelCreating(modelBuilder);
}
How do you make EF not allow deletion of a related entity?
You want to prevent deleting things that is in used, right? Is course and enrollments a many to many relationship? Many to many will not cascade on delete by default. Try to change to this.
public class Enrollment
{
public int EnrollmentId { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Need this to remove the cascade convention.
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
I'm using this kind of model for a 0..1 to many relationship. A Page must either have a valid book id or null.
public class Book
{
[Key]
public Guid Id { get; set; }
public virtual List<Page> Pages { get; set; }
}
public class Page
{
[Key]
public Guid Id { get; set; }
public virtual Book Book { get; set; }
}
I want to add cascading deletes, so that if a book is deleted then all of its pages are also deleted, not set to null.
I can (only?) do this with the fluent api:
modelBuilder.Entity<Page>()
.HasOptional(a => a.Book)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
Using [Required] is not suitable, because the field is not required.
However, this creates another column Book_Id1, index and foreign key in the database, rather than adding cascading deletes on the existing FK, because it's defined twice.
If I comment out the Book.Pages property, it works, but I lose the ability to call book.Pages and have to instead call dbcontext.Pages.Where(p => p.Book.Id == book.Id), which is not ideal because I don't want the calling code to have to know about the dbcontext object.
Is there a way to have both the Book.Pages property and cascading deletes? Perhaps setting both to use the same FK name?
here what you can do
public class Book
{
[Key]
public Guid Id { get; set; }
public virtual List<Page> Pages { get; set; }
}
public class Page
{
[Key]
public Guid Id { get; set; }
public Guid BookId { get; set;}
//[ForeignKey("BookId")] you can add the fluent here or during entity builder
public virtual Book Book { get; set; }
}
modelBuilder.Entity<Page>()
.HasOptional(a => a.Book)
.WithMany(a=>a.Pages)
.HasForeignKey(a=>a.BookId)
.WillCascadeOnDelete(true);
var pages= dbcontext.Pages.Where(p => p.BookId == book.Id); // this will work
this code should work normally for you
i think in codefirst you have to try this
dbcontext.Page.RemoveRange(book.Pages);
dbcontext.Book.Remove(book);
dbContext.SaveChanges();
I have been trying to figure out if it is possible to create an association in EF without the use of all keys.
Below is an example where there is a combination key in author, but I only have 1 part of that key in book. My question is how do I make a Navigation property without all of the keys?
[Table("Book")]
public class Book {
[Key]
public int ID { get; set; }
public string AuthorLastName { get; set; }
public virtual Author Author { get; set; }
}
[Table("Author")]
public class Author {
[Key, Column(Order=0)]
public string AuthorFirstName { get; set; }
[Key, Column(Order=1)]
public string AuthorLastName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
internal class BookConfig : EntityTypeConfiguration<Book> {
public BookConfig()
{
HasRequired(hr => hr.Author)
.WithMany(wm => wm.Books)
.HasForeignKey(fk => new {
fk.AuthorLastName
});
}
}
This is obviously not going to work since I don't have all of the full combination key in book to associate it to author in this way.
You can do something like that:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
This will give you a manual control on the key; But the Table in the database must have a primary key! I'm wonderung why ou need something like that I think the problem somewhere else.
You cannot do that because it's a many to many relation.
In your example, if you only take AuthorLastName there can be several authors with the same last name. So there are many elements in this side of the relation. And obviously there are many books on the other side (an author can write many books).
So, definitely, you cannot model it as a one-to-many relation.
Fortunately, someone has explained this problem of books and authors before..
I'm trying to convert the following model (see image below) to Code First. I've tried various combinations involving ForeignKey and InverseProperty attributes with no luck. I've found this answer but it seems that combinations of ForeignKey and InverseProperty cause a different behaviour.
The attached source code gives the following error:
Unable to determine the principal end of an association between the types 'InversePropertyTest.Author' and 'InversePropertyTest.Book'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
This is my model with EDMX
Sample code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InversePropertyTest
{
public class Author
{
public int AuthorId { get; set; }
public Nullable<int> CurrentlyWorkingBookId { get; set; }
[InverseProperty("Author")] public ICollection<Book> Books { get; set; }
[ForeignKey("CurrentlyWorkingBookId"), InverseProperty("EditoredBy")] public Book CurrentlyWorkingBook { get; set; }
}
public class Book
{
public int BookId { get; set; }
public int AuthorId { get; set; }
[ForeignKey("AuthorId"), InverseProperty("Books")] public Author Author { get; set; }
[InverseProperty("CurrentlyWorkingBook")] public Author EditoredBy { get; set; }
}
public class SimpleContext : DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
class Program
{
static void Main(string[] args)
{
using (var context = new SimpleContext())
{
IList<Author> authors = (from a in context.Authors select a).ToList();
IList<Book> books = (from b in context.Books select b).ToList();
}
}
}
}
Any help is greatly appreciated
When you use [InverseProperty] at both ends of a 1:1 association it is not clear who the principal should be. The principle is the entity the other end (the dependent) refers to by a foreign key. Even though you tell EF that EditoredBy and CurrentlyWorkingBookId both are part of one association it still would be possible to have a foreign key field for EditoredBy in Book (that wouldn't show in the class model).
Admittedly, one could contend that you've told EF enough to create the database model properly. EF could have logic that says: if I've been told about one foreign key in a 1:1 association, then I know who the principle should be. However, unfortunately it doesn't.
So I would use the fluent API to model this:
public class Author
{
public int AuthorId { get; set; }
public ICollection<Book> Books { get; set; }
public Book CurrentlyWorkingBook { get; set; }
}
public class Book
{
public int BookId { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
public Author EditoredBy { get; set; }
}
In OnModelCreating:
modelBuilder.Entity<Author>()
.HasMany(a => a.Books)
.WithRequired(b => b.Author)
.HasForeignKey(b => b.AuthorId);
modelBuilder.Entity<Author>()
.HasOptional(a => a.CurrentlyWorkingBook)
.WithOptionalDependent(b => b.EditoredBy)
.Map(m => m.MapKey("CurrentlyWorkingBookId"));
Personally, I like the fluent API because the lambda expressions allow compile-time checks and it is much more conspicuous which ends comprise one association.
As you see, CurrentlyWorkingBookId can not be part of the class model in this scenario. That is because an OptionalNavigationPropertyConfiguration (the return type of WithOptionalDependent) doesn't have HasForeignKey method. I'm not sure why not. I think it should be possible to set a primitive FK value (CurrentlyWorkingBookId) as well as a reference property (CurrentlyWorkingBook).