Entity Framework cascade delete configuration - entity-framework

here are two entities of my model with fluent entityframework configuration of it
Player.cs
public class Player
{
public string Name { get; set; }
public virtual Statistics Statistics { get; set; }
}
Statistics.cs
public class Statistics
{
public int GamePlayed { get; set; }
public int Assists { get; set; }
public int Goals { get; set; }
}
DbContextClass
modelBuilder.Entity<Player>()
.HasOptional(x => x.Statistics)
.WithMany()
.Map(x => x.MapKey("StatisticsId"));
In the end, a foreignKey named 'StatisticsId' is create on my Player Table which is ok. I want on a player deletion, to cascadeDelete related stats. Here's my problem, adding WillCascadeDelete to my statement as
modelBuilder.Entity<Player>()
.HasOptional(x => x.Statistics)
.WithMany()
.Map(x => x.MapKey("StatisticsId"))
.WillCascadeOnDelete(true);
results as deleting the player when statistics are deleted. How could I make this work the opposite way by keeping StatisticsId foreignKey on the player table ?
The main point here is that Statistics can 'live alone' without any Player related. Is it possible to set Entity Framework to auto delete related Statistics or this has to be done manually ?

I assume you just need to add WillCascadeOnDelete to Statistics :
modelBuilder.Entity<Statistics>()
.WillCascadeOnDelete(true);
I haven't tested though.

Related

Masstransit sagas and Entity Framework repository model changes

I've been playing around with the masstransit sample from here https://github.com/MassTransit/Sample-ShoppingWeb
Allthough i have updated to the latest version(3.3.5) of masstransit and everything works fine.
I want to add ShoppingCartItems to my ShoppingCart so i added it to the model and the mapping like this.
public class ShoppingCartMap :
SagaClassMapping<ShoppingCart>
{
public ShoppingCartMap()
{
Property(x => x.CurrentState)
.HasMaxLength(64);
Property(x => x.Created);
Property(x => x.Updated);
Property(x => x.UserName)
.HasMaxLength(256);
Property(x => x.ExpirationId);
Property(x => x.OrderId);
HasMany(c => c.ShoppingCartItems);
}
}
public class ShoppingCart :
SagaStateMachineInstance
{
public string CurrentState { get; set; }
public string UserName { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
/// <summary>
/// The expiration tag for the shopping cart, which is scheduled whenever
/// the cart is updated
/// </summary>
public Guid? ExpirationId { get; set; }
public Guid? OrderId { get; set; }
public Guid CorrelationId { get; set; }
public virtual List<ShoppingCartItem> ShoppingCartItems { get; set; } = new List<ShoppingCartItem>();
}
public class ShoppingCartItem
{
public Guid? Id { get; set; }
public string Name { get; set; }
public Guid? OrderId { get; set; }
}
This is run at startup:
SagaDbContextFactory sagaDbContextFactory =
() => new SagaDbContext<ShoppingCart, ShoppingCartMap>(SagaDbContextFactoryProvider.ConnectionString);
_repository = new Lazy<ISagaRepository<ShoppingCart>>(
() => new EntityFrameworkSagaRepository<ShoppingCart>(sagaDbContextFactory));
The problem i get is an error message saying the model has changed. If i drop the database and run the solution from scratch it works but i dont want to drop my entire DB every time i need to make a change in my saga class.
My plan is to build my ShoppingCart through the saga and when i reach my finished state i will use the saga context(ShoppingCart) to create and persist real orders. Maybe i am going by this all wrong and have missunderstood the whole concept of sagas? If so how would one go about sagas that have complex object graphs?
Saga persistence just saves your saga instance objects to some tables, according to your mapping. You can use your persistence layer's own schema update tools to fix this. I do not think this has anything to do with MassTransit. For EF you can use EF code-first migrations. For NH you can use the built-in schema update. For document databases like MondoDb or RavenDb you just do nothing.
In any case, think about this as a normal database schema change task. You have to put some effort in it like in any other database schema change. For example, you need to consider migrations required to fix your existing saga when you update the schema. As for any other schema change you would need to have some scripts or code to fix this. The same applies for document databases as well although you do not need to have schema update scripts or code for every change, but at least for those that require to change existing saga documents.

Entity Framework Cascading Delete

First of all, apologies if I'm missing some basic stuff here but I'm new to EF and still getting my head around setting up the DB code first....
I'm having a similar problem to this Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths but can't seem to work out from the comments there what I need to do with my particular model. When I attempt to update database after adding in public virtual Actor actor { get; set; } to my UseCase class, I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.UseCase_dbo.Actor_ActorID' on table 'UseCase' 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.
I know it must be something to do with the way that my FK constraints are set up (probably something to do with deleting a use case meaning that I'll end up deleting data from multiple other tables).
I tried turning off cascading delete, but still get the error:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//prevent table names created by entity framework being pluralised
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//Turn off delete cascades between parent child tables. May need to put this back in future, but for the time being it is stopping the database being updated through the package manager console (error is that a foregin key constraint may cause cycles or multiple cascade paths)
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
Here are my models. What should happen is that only if a project is deleted should it's use cases or actors be deleted. Actors should not be deleted when a UseCase is, because they may be involved in other UseCases. Can anyone point to what I need to change?
Finally, the correct model indeed is this Project > Actors > Use Cases. I assume that I should just remove public virtual int ProjectID { get; set; } and public virtual Project project { get; set; } from UseCase?
Learning hurts!
public class Project
{
public virtual int ID {get; set;}
[DisplayName ("Project Name")]
public virtual string ProjectName { get; set; }
[DisplayName("Client")]
public virtual string ClientID { get; set; }
public virtual string Description { get; set; }
[DisplayName("Use Cases")]
public virtual ICollection <UseCase> UseCases { get; set; }
}
public class UseCase
{
public virtual int ID { get; set; }
[Required]
public virtual int ProjectID { get; set; }
public virtual int ActorID { get; set; }
[Required]
public virtual Actor actor { get; set; }
public virtual string Title { get; set; }
public virtual Level? Level { get; set; }
public virtual string Precondition { get; set; }
public virtual string MinimalGuarantee { get; set; }
public virtual string SuccessGuarantee { get; set; }
public virtual ICollection<Step> Steps { get; set; }
public virtual ICollection<Extension> Extensions { get; set; }
public virtual ICollection<Query> Queries { get; set; }
}
public class Actor
{
public virtual int ID { get; set; }
public virtual int projectID { get; set; }
public virtual Project project { get; set; }
public virtual string Title { get; set; }
[DataType(DataType.MultilineText)]
public virtual string Description { get; set; }
}
UPDATED So, here is my modified code based on feedback below. I'm still getting the same error, either when I run the application and it tries to create the DB or when I try to update the database through package manager Update-Database. Driving me crazy.
To me, the code below says if I delete an actor, delete the use cases for that actor too. If I delete a project, delete the actors for the project and therefore delete the use cases for each actor too. But if I delete a project, don't delete the use cases. Clearly, I'm misunderstanding something quite badly :-(
modelBuilder.Entity<Actor>()
.HasMany(a => a.useCases)
.WithRequired(uc => uc.actor)
.HasForeignKey(uc => uc.ActorID)
.WillCascadeOnDelete(true); // and this works
modelBuilder.Entity<Project>()
.HasMany(p => p.actors)
.WithRequired(a => a.project)
.HasForeignKey(a => a.projectID)
.WillCascadeOnDelete(true); // this works
modelBuilder.Entity<Project>()
.HasMany(p => p.UseCases)
.WithRequired(uc => uc.project)
.HasForeignKey(uc => uc.ProjectID)
.WillCascadeOnDelete(false); // disable this cascading delete
You need to disable cascade deletes for all but one of the possible paths. In your case you have the following paths:
Project -> UseCase
Project -> Actor -> UseCase
You can allow a single path for cascading deletion of UseCase - via the Project entity or Actor entity. However, if we disable cascading deletes in the Project -> UseCase path, we'll still achieve a cascading delete via Actor:
modelBuilder.Entity<Project>()
.HasMany( p => p.UseCases )
.WithRequired( uc => uc.Project )
.HasForeignKey( uc => uc.ProjectID )
.WillCascadeOnDelete( false ); // disable this cascading delete
modelBuilder.Entity<Project>()
.HasMany( p => p.Actors )
.WithRequired( a => a.Project )
.HasForeignKey( a => a.ProjectID )
.WillCascadeOnDelete( true ); // this works
modelBuilder.Entity<Actor>()
.HasMany( a => a.UseCases )
.WithRequired( uc => uc.Actor )
.HasForeignKey( uc => uc.ActorID )
.WillCascadeOnDelete( true ); // and this works
Side note:
Your model has a data inconsistency hazard - both Actor and UseCase have a FK to Project via ProjectID, but there is nothing in the model to enforce the Actor referenced by a UseCase has the same ProjectID - an Actor from "Project 1" could be reference by a UseCase from "Project 2". You could include the ProjectID in the Actor PK and then in the UseCase->Actor FK, ensuring that the Actor referenced by a UseCase belongs to the same Project, but this would technically violate the 2NF.
The 'proper' model is probably a Project->Actors->UseCases hierarchy, simply requiring you to join through Actors to get a Project's UseCases
You need to make ActorID in your UseCase class as a nullable int. EF is throwing that error because it sees 2 foreign keys that are required in a single class. Having that would create multiple cascade paths--something that SQL Server is, unfortunately, ill-equipped to handle.
In any case, making Actor optional on your UseCase class will mean that the Actor won't be deleted when the UseCase is, which I believe is your intent.

Entity Framework Generated Column Names

I have a Job Entity which has 2 collections of the same type
public virtual ICollection<Device> ExistingDevices { get; set; }
public virtual ICollection<Device> NewDevices { get; set; }
On the Device Entity, it refers back to the Job
public int JobId { get; set; }
public virtual Job Job { get; set; }
On the surface, this works just fine, however on the database, if you look at a device you see this
//Devices Table in Db
|JobId | Job_Id | Job_Id1 |
My setup includes Entity configuration objects for using fluent API, however I have not worked out how to fix this. The first JobId is fine, it is a perfect description of the data. The second two refer to the ExistingDevices and NewDevices lists they belong to. The headers are not at all descriptive.
Is it possible to rename these columns to something more appropriate?
//Edit
It has the FK JobId but also if the device is in the ExistingDevices list, the JobId also gets put into Job_Id and Job_Id1 is null. If the device belongs to the NewDevices list, the Job_Id is null and the Job_Id1 has the JobId in it.
Naming the Job_id to ExistingDevices and Job_Id1 to NewDevices would make it much clearer in Db.
Update
Having slept on it, I decided it was a design fault.
I changed the Device Model to have
public bool NewDevice { get; set; }
and changed the Job Model by removing the 2 existing ICollections and adding
public virtual ICollection<Device> Devices { get; set; }
Rather than having two device collections, I now have one, with a properly descriptive FK. In the database a 1 or 0 will indicate new or existing device.
You have two one to many relationship, the database will have two foreign key columns on the dependent entity (Device). JobId might represent ExistingDevices and JobId1 might represent NewDevices.
To be clear you should define two navigation properties as follow.
public int? ExistingJobId { get; set; }
public virtual Job ExistingJob { get; set; }
public int? NewJobId { get; set; }
public virtual Job NewJob { get; set; }
Then can configure the relationship using Fluent Api.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Device>()
.HasOptional(x => x.ExistingJob)
.WithMany(x => x.ExistingDevices)
.HasForeignKey(x => x.ExistingJobId);
.WillCascadeOnDelete(true);
modelBuilder.Entity<Device>()
.HasOptional(x => x.NewJob)
.WithMany(x => x.NewDevices)
.HasForeignKey(x => x.NewJobId)
.WillCascadeOnDelete(false);
}
Note, one foreign key is defined without cascading delete (false) because multiple cascading delete is not allowed.
update: the required existing job and new job have been changed into optional.

Entity Framework Code First - Navigation property on Composite Primaty Key

Firebird 2.5
Entity Framework 5
FirebirdClientDll 3.0.0.0
Hi, I'm trying to access my legacy database with the Entity Framework (Code First).
I got the problem that the database does not use foreign keys...
public class CUSTOMERS
{
public int CUSTOMERID { get; set; }
public string NAME{ get; set; }
}
public class INVOICES
{
public int INVOICEID{ get; set; }
public int CUSTOMERID{ get; set; }
public virtual CUSTOMERS CUSTOMERS { get; set; }
}
public class INVOICEContext : DbContext
{
public DbSet<CUSTOMERS> CUSTOMERS{ get; set; }
public DbSet<INVOICES> INVOICES{ get; set; }
public INVOICEContext(DbConnection connectionString) : base(connectionString, false)
{
Database.SetInitializer<INVOICEContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
/*modelBuilder.Entity<INVOICES>().HasRequired(b => b.CUSTOMERS)
.WithMany()
.Map(p => p.MapKey("INVOICEID"));*/ //Doesn't work because INVOICEID is defined
modelBuilder.Entity<INVOICES>().HasKey(a => new { a.INVOICEID, a.CUSTOMERID});
modelBuilder.Entity<CUSTOMERS>().HasKey(a => new { a.CUSTOMERID });
base.OnModelCreating(modelBuilder);
}
}
Normally I could remove the property CUSTOMERID from the class INVOICES, but in this case it is part of the primary key...
I found many threads which suggested to use IsIndependent, but it seems to be removed from the Entity Framework 5 (or 4.1).
I hope you can understand my poor English and maybe give me a hint what I'm doing wrong ^^
I don't know what you mean with "the database does not use foreign keys". So, maybe the following is not the answer you are looking for. But I'd say that you can use your relationship mapping that is commented out in your code if you replace ...MapKey... by HasForeignKey and use CUSTOMERID instead of INVOICEID as the foreign key property:
modelBuilder.Entity<INVOICES>()
.HasRequired(b => b.CUSTOMERS)
.WithMany()
.HasForeignKey(b => b.CUSTOMERID);
The model and the rest of the mapping is fine in my opinion. Your relationship is an identifying relationship (that means that the foreign key is part of a composite primary key) which is a valid mapping with Entity Framework.
Try this ...
modelBuilder.Entity<INVOICES>()
.HasRequired(i => i.CUSTOMERS)
.WithMany()
.HasForeignKey(i => i.CUSTOMERID);

EF 4.1 Code First ModelBuilder HasForeignKey for One to One Relationships

Very simply I am using Entity Framework 4.1 code first and I would like to replace my [ForeignKey(..)] attributes with fluent calls on modelBuilder instead. Something similar to WithRequired(..) and HasForeignKey(..) below which tie an explicit foreign key property (CreatedBySessionId) together with the associated navigation property (CreatedBySession). But I would like to do this for a one to one relationsip instead of a one to many:
modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId)
A more concrete example is below. This works quite happily with the [ForeignKey(..)] attribute but I'd like to do away with it and configure it purely on modelbuilder.
public class VendorApplication
{
public int VendorApplicationId { get; set; }
public int CreatedBySessionId { get; set; }
public virtual Session CreatedBySession { get; set; }
}
public class Session
{
public int SessionId { get; set; }
[ForeignKey("CurrentApplication")]
public int? CurrentApplicationId { get; set; }
public virtual VendorApplication CurrentApplication { get; set; }
public virtual ICollection<VendorApplication> Applications { get; set; }
}
public class MyDataContext: DbContext
{
public IDbSet<VendorApplication> Applications { get; set; }
public IDbSet<Session> Sessions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Session>().HasMany(x => x.Applications).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId).WillCascadeOnDelete(false);
// Note: We have to turn off Cascade delete on Session <-> VendorApplication relationship so that SQL doesn't complain about cyclic cascading deletes
}
}
Here a Session can be responsible for creating many VendorApplications (Session.Applications), but a Session is working on at most one VendorApplication at a time (Session.CurrentApplication). I would like to tie the CurrentApplicationId property with the CurrentApplication navigation property in modelBuilder instead of via the [ForeignKey(..)] attribute.
Things I've Tried
When you remove the [ForeignKey(..)] attribute the CurrentApplication property generates a CurrentApplication_VendorApplicationId column in the database which is not tied to the CurrentApplicationId column.
I've tried explicitly mapping the relationship using the CurrentApplicationId column name as below, but obviously this generates an error because the database column name "CurrentApplicationId" is already being used by the property Session.CurrentApplicationId:
modelBuilder.Entity<Session>().HasOptional(x => x.CurrentApplication).WithOptionalDependent().Map(config => config.MapKey("CurrentApplicationId"));
It feels like I'm missing something very obvious here since all I want to do is perform the same operation that [ForeignKey(..)] does but within the model builder. Or is it a case that this is bad practise and was explicitly left out?
You need to map the relationship as one-to-many and omit the collection property in the relationship.
modelBuilder.Entity<Session>()
.HasOptional(x => x.CurrentApplication)
.WithMany()
.HasForeignKey(x => x.CurrentApplicationId)