EfCore.Shaman
EfCore.Shaman copied to clipboard
Configuring Foreign Key properties in Annotation
In EF core default behavior for FK is that it automatically generates Index for it and set DeleteBehavior to Cascade. Both are practical but sometime you want to change it, which can be done in Migration file after it is generated.
Another way, better, would be to configure it before generating migration, so in fluentAPI we have:
a) OnDelete method
modelBuilder.Entity<Movie>().HasOne(p => p.Genre) .WithMany(b => b.Movies) .OnDelete(DeleteBehavior.Restrict);
b) and to remove Index from FK Column.
var index = (Index)modelBuilder.Entity<MyEntity>().HasIndex(e => e.Name).Metadata;
index.DeclaringEntityType.RemoveIndex(index.Properties, runConventions: false);
However it would be best if these could be configured in Annotation, since goal is all in one place.
I would give Cascade feature higher priority over HasIndex when it comes to implementation, if they would not be implemented together.
One approach that comes to my mind at the moment is to use [ForeignKey]
attribute, and to extend it somehow. Maybe make partial class [ForeignKeyAttribute] with another constructor
(string name, DeleteBehavior deleteBehavior, hasIndex = true).
Or make new attribute for this named [ForeignKeyExtendedAttribute]
or what ever name suites best:
(string name, DeleteBehavior deleteBehavior = DeleteBehavior.Cascade, hasIndex = true).
Do you think this could also, relativly easily, be added to Shaman library?
Yes. Relations definition language
is not well designed. We make definition is on storage level so we're involved in tuning foreign keys. I wish I could define relations on more abstract level.
Moreover I don't know why in fluent API we have DeleteBehavior with only 3 values Restrict , SetNull and Cascade but CreateTableBuilder<TColumns>.ForeignKey (used with MigrationBuilder) has more possibilities
- it has both ReferentialAction onUpdate and ReferentialAction onDelete
- ReferentialAction has 5 values NoAction, Restrict, Cascade, SetNull, SetDefault
I have a plan to extend Shaman with possibility to define FK behaviour with attributes.
I hate reach-your-right-leg-to-the-left-ear
code available with FluentApi
I noticed, enums should have the same values, or even they could have only one Enum for both usage.
Great, looking forward to it. Write here once it's done and I'll test it, can help with writing Docs as well.
I have asked EF team on GitHub about DeleteBehavior, here is the issue: https://github.com/aspnet/EntityFramework/issues/7530
How is this now being used, I can't find example of it in code nor in test. Is it new attribute, named how? or extension of existing.
Sorry. I will put some info on main web page.
Thx