Entity Framework - Delete join table record when one linked record is deleted - entity-framework-6

public class Club
{
public int ClubId { get; set; }
public string Name { get; set; }
public ICollection<Membership> Memberships { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public ICollection<Membership> Memberships { get; set; }
}
public class Membership
{
public int ClubId { get; set; }
public int PersonId { get; set; }
public Club Club { get; set; }
public Person Person { get; set; }
}`
...
modelBuilder.Entity<Person>()
.HasMany(p => p.Memberships)
.WithRequired(m => m.Person)
.WillCascadeOnDelete(true);
Above is a simple set up of two independent entities: Club and Person, which may be joined via membership.
I had thought that I could simply retrieve a Person, delete it, and then rely on cascade deleting to remove any Membership records and leave the associated Clubs in place (they exist independently).
Similarly, I had thought that I could simply retrieve a Club, delete it, and then rely on cascade deleting to remove amy Membership records and leave the associated Persons in place (they exist independently).
It seems that when I remove a "Person", EF tries to set the value of Membership.PersonId to null causing a db violation.
Have I misunderstood cascade deleting? And how could I achieve the desired result?
I guess that I could retrieve Person.Include("Membership") and then enumerate each membership and mark as deleted and then finally mark the Person as deleted ... but is this really required or am I missing a trick?

Related

Entity Framework database mapping relationships (Duplicate creation using Seed() method)

I created a post with an issue and another issue.
These can be looked at for references but i consider them as handled.
My question arising from these issues and the action i (need or not need) to apply bothers me because i don't quite understand EF its behavior and expectations.
I have a Product, PurchasePrice and SalesPrice entity where my initial thought was that 1 Product can have multiple PurchasePrices but that 1 PurchasePrice only can exist in 1 Product (same for SalesPrice).
Therefore these relations:
// NOTE that BaseEntity just has a "int ID" prop and datetimes/stamps
public class Product : BaseEntity
{
public ICollection<PurchasePrice> PurchasePrices { get; set; }
public ICollection<PurchasePrice> SalesPrices { get; set; }
}
public class PurchasePrice:BaseEntity
{
public Product Product { get; set; }
}
public class SalesPrice:BaseEntity
{
public Product Product { get; set; }
}
Now, lets add a Supplier Entity to it because that is why i seperate Sales & Purchase apart and don't create an Enum out of it, because 1 Product (in database) can have multiple suppliers, each having their own Sales/Purchase prices AND another Productnumber value.
So above becomes:
public class Product : BaseEntity
{
public ICollection<PurchasePrice> PurchasePrices { get; set; }
public ICollection<PurchasePrice> SalesPrices { get; set; }
// added
public ICollection<Supplier> Suppliers { get; set; }
}
public class PurchasePrice:BaseEntity
{
public Product Product { get; set; }
// added
public Supplier Supplier { get; set; }
}
public class SalesPrice:BaseEntity
{
public Product Product { get; set; }
// added
public Supplier Supplier { get; set; }
}
// added Entity Supplier into the party
public class Supplier : BaseEntity
{
public ICollection<Product> Products { get; set; }
public ICollection<PurchasePrice> PurchasePrices { get; set; }
public ICollection<SalesPrice> SalesPrices { get; set; }
}
Lets continue a little furhter because it doesn't stop there, i want to keep track of these Product-Supplier-Prices relations so i created a Entity called 'ProductSupplierForContract' which would have the following structure:
public class ProductSupplierForContract:BaseEntity
{
public string ProductnumberValue { get; set; }
public int Product_Id { get; set; }
public int Supplier_Id { get; set; }
public int? Contract_Id { get; set; }
public virtual Product Product { get; set; }
public virtual Supplier Supplier { get; set; }
public virtual Contract Contract { get; set; }
}
Finally i have a Contract Entity which has the following structure:
public class Contract:BaseEntity
{
[Required]
public ICollection<Product> Products { get; set; }
public ICollection<ProductSupplierForContract> ProductSupplierForContracts { get; set; }
}
So Product becomes:
public class Product : BaseEntity
{
public ICollection<PurchasePrice> PurchasePrices { get; set; }
public ICollection<PurchasePrice> SalesPrices { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
// added
public ICollection<Contract> Contracts { get; set; }
}
Custom Seeding (inherits from DropCreateDatabaseAlways):
protected override void Seed(ApplicationDbContext context)
{
PurchasePrice purchaseprice = new PurchasePrice((decimal)17.70);
ctx.PurchasePrices.Add(purchaseprice);
Product product1 = new Product("test product 1",purchaseprice);
ctx.Products.Add(product1);
base.Seed(ctx);
}
I also have mappings defined in Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// setting the Product FK relation required + related entity
modelBuilder.Entity<Entity.ProductSupplierForContract>().HasRequired(psfc => psfc.Product)
.WithMany(p => p.ProductSupplierForContracts)
.HasForeignKey(psfc => psfc.Product_Id);
// setting the Supplier FK relation required + related entity
modelBuilder.Entity<Entity.ProductSupplierForContract>().HasRequired(psfc => psfc.Supplier)
.WithMany(s => s.ProductSupplierForContracts)
.HasForeignKey(psfc => psfc.Supplier_Id);
// setting the Contract FK relation required + related entity
modelBuilder.Entity<Entity.ProductSupplierForContract>().HasOptional(psfc => psfc.Contract)
.WithMany(c => c.ProductSupplierForContracts)
.HasForeignKey(psfc => psfc.Contract_Id);
}
Now, initially i didn't had any issues and i really really don't understand what has brought up this sudden change that i now got duplicates Products when i seed my database. I can strip it down to just adding a simple PurchasePrice with a value and a Product having a reference to this PurchasePrice and there is my duplicate.
Changing the relation inside the PurchasePrice class of the Entity Product, to a ICollection doesn't create a duplicate but i don't want this collection because it is not a Many to Many relation ...
I have tried enormous amounts of things but nothing that "resolved" this (if this is a problem to start with, for me yes but maybe not for EF) like removing inhertance BaseEntity, changinge Mapping (Fluent AND annotations), changed the way i seeded and initialized everthing, defining ID's myself, you name it ...
Mind that the purpose is not to optimize the way i seed in anyway but to have a decent working Model AND to understand what EF does and what it wants.
My questions:
Why is this duplicate occuring/appearing ?
If i want to be able to have 1 instance holding the relation of
Price-Supplier-Product-Contract, how should i do this? Answer is here
I fixed my problem by redesigning the model. I have added a additional Entity ProductForSupplier which holds the relation of a Product & Supplier and a Productnumber.
public class ProductForSupplier:BaseEntity
{
public string ProductnumberValue { get; set; }
[Required]
public Product Product { get; set; }
[Required]
public Supplier Supplier { get; set; }
}
Added a Entity ProductsForContract which will hold the amount of a Product-Supplier relation for 1 contract:
public class ProductsForContract
{
public int ProductsForContractId { get; set; }
public int Amount { get; set; }
public ProductForSupplier ProductForSupplier { get; set; }
public Contract Contract { get; set; }
}
And the Existing Entity ProductSupplierForContract becomes:
public class ProductSupplierForContract:BaseEntity
{
public ICollection<ProductsForContract> ProductsForContract { get; set; }
[Required]
public Contract Contract { get; set; }
}
This gives me the flexibility to keep relations of any kind between the entities and also has taken care of the duplicate (which i still don't know the cause of).

Multiple tables update MVC .net

I am new to MVC and this is my function. There are three tables (Order, OrderNotes, Notes), ID is their primary key. One Order can have many Notes, the table OrderNotes has foreign key OrderID(from Booking table) and NotesID(from Notes table). I want to have a Order Edit page to display individual Order (FirstName, LastName), also display a list of its Notes. Here is my DB structure:
Booking table:
{ID,
FirstName,
LastName
}
BookingNotes table:
{ID,
BookingID,
NotesID
}
Notes table:
{ID,
NoteName,
StatusID
}
So how can I implement the list of Notes since it's from multiple tables? It will be able to Create New Note, Delete existing Note in the list row record, not Edit. Linq used in DB query. Thanks.
It would be a better idea to have only 2 tables:
public class Book
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Navigational properties
public virtual List<Note> Notes { get; set; }
}
public class Note
{
public int ID { get; set; }
public int BookID { get; set; }
public string NoteName { get; set; }
public int StatusID { get; set; }
// Navigational properties
public virtual Book Book { get; set; }
public virtual Status Status { get; set; }
}
A third table is useful when you want to reuse the same Note for a different booking. However i think this is not the case.
So to retrieve data for your context make sure you have the DbSet<Book>
public class ApplicationDbContext : DbContext
{
public virtual DbSet<Book> Bookings { get; set; }
}
In your controller (or better in a repository class):
var BookingID = 10; // this is parameter passed to the function
var myBooking = this.dbContext.Bookings
.Include(p => p.Notes)
.ThenInclude(p => p.Status)
.FirstOrDefault(p => p.ID == BookingID);
Map the retrieved booking to a ViewModel, pass it to the View and you're good to go.

Specify foreign key in Entity Framework when not defined in database

I am working with an existing database where no foreign keys are defined. I can't change the database but would like to define relationships in my entity model. For example, the People table has all the names of the people but the Coaches table only has a reference to the PeopleId. I would like to define that relationship in my Coaches entity object.
I turns out that with more testing it doesn't seem to matter that the database has not defined the foreign key. I'm still able to bring in the associated tables info. Additional testing will be needed because referential integrity is not enforced by the database. However with this table definition and model definition, my person data is being brought in.
[Key]
public int CoachID { get; set; }
public Nullable<int> CompanyID { get; set; }
public Nullable<int> SeasonID { get; set; }
public int PeopleID { get; set; }
public Nullable<int> PlayerID { get; set; }
public string ShirtSize { get; set; }
public string CoachPhone { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string CreatedUser { get; set; }
public virtual Person Person { get; set; }
modelBuilder
.Entity<Coach>()
.ToTable("Coaches")
.HasRequired(p => p.Person)

ASP.NET MVC 4 Multiple Foreign Keys Referencing Single Parent Entity

I am trying to develop an ASP.NET MVC 4 application where players can be rated according to their Offence, Defence and Assist skills. Offence, Defence and Assist are foreign keys on Player table referencing the same lookup table - Rating.
I have the following parent entity:
public class Rating
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
And child entity:
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public int OffenceRatingId { get; set; }
[ForeignKey("OffenceRatingId")]
public virtual Rating OffenceRating { get; set; }
public int DefenceRatingId { get; set; }
[ForeignKey("DefenceRatingId")]
public virtual Rating DefenceRating { get; set; }
public int AssistRatingId { get; set; }
[ForeignKey("AssistRatingId")]
public virtual Rating AssistRating { get; set; }
}
Building and scaffolding went fine but when I run the app, I get the following error:
Introducing FOREIGN KEY constraint 'FK_dbo.Players_dbo.Ratings_DefenceRatingId' on table 'Players' 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 new to MVC and have no idea what I am missing here. Any help with this will be greatly appreciated. Thanks.
By default, Entity Framework has a Cascade on Delete convention. When two entities have foreign keys to each other, it causes a circular reference and Cascade on Delete can't be applied to both entities.
The simplest solution is to remove the cascade on delete convention, and apply it on a case by case basis.

How to create One-to-many relationship in Entity Framework 4.1 using Code First and Data Annotations?

I'm struggling with creating a simple one-to-many relationship using Code First in EF. I want it to generate daatabase for me but couldn't figure out how to write these classes so it would create it.
I have these classes:
public class Book
{
public int ID { get; set; }
public string Author { get; set; }
public ICollection<Page> Pages { get; set; }
}
public class Page
{ [Key]
public int BookID { get; set; }
public Book Book { get; set; }
public string OtherField { get; set; }
}
But I get error while it ties to generate database:
Unable to determine the principal end of an association between the types 'MvcApplication1.Models.Page' and 'MvcApplication1.Models.Book'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
I just want to generate two simple tables, "Book" with ID as primary key, and Page with BookID as a primary and foreign key. It really should be simple but I just can't figure it out.
But that is not one-to-many relationship. That is one-to-one relation ship which says that each book has exactly one page. The error says that it cannot determine if the book or the page is principal in the one-to-one relation.
You must modify your entities like this:
public class Book
{
public int ID { get; set; }
public string Author { get; set; }
public virtual ICollection<Page> Pages { get; set; }
}
public class Page
{
public int ID { get; set; }
public int BookID { get; set; }
public virtual Book Book { get; set; }
public string OtherField { get; set; }
}

Resources