I'd like to add unique constraint using model builder in ASP.NET Core
.NET 5
EF Core 5..
Here is what I found:
modelBuilder.Entity<Ticker>()
.HasIndex(r => r.Name)
.IsUnique();
However after updating database it adds index instead of constraint.
Is there the way to add constraint?
Thanks for the answer.
Although you use .HasIndex(r => r.Name).IsUnique(),it will create a unique Index instead of Constraint. But the effect are the same. It will prevent you adding duplicated value for Name.
However after updating database it adds index instead of constraint. Is there the way to add constraint?
If you must add Constraint, I suggest you use HasAlternateKey method which enables you to create an alternate key by placing a unique constraint:
modelBuilder.Entity<Ticker>()
.HasAlternateKey(r => r.Name);
Then you can see it adds the unique constraint like below in database:
Related
I'm trying to add a Unique Constraint across a property "Blah" and a Shadow FK
modelBuilder.Entity<ParameterOption>().HasIndex("Blah", "ShadowForeignKey").IsUnique();
But when I try and migrate, it doesn't recognise "ShadowForeignKey".
I have tried using ...
modelBuilder.Entity<ParameterOption>().Property<string>("ShadowForeignKey")
which I thought might let the model be able to use the shadow FK
But that ends up needing a migration where it tries to create ...
ShadowForeignKey1
Because ShadowForeignKey already exists as a shadow property.
Please help!
I was an ordering issue in OnModelCreating the Shadow Property Foreign Key was introduced lower in the file.
To reference a Shadow Property it (maybe unsuprisingly) needs to be higher in the file.
I'm trying to add a check constraint to a table via EF Core 1.1 using Code First.
The only answer I found was defining my constraint in the migration in a way like this:
migrationBuilder.Sql("ADD CONSTRAINT CK_Column CHECK (Column >= X);");
My ER-Modell looks like this:
Min-Max Relationship
In my picture you can see that a "Process" has minimum 2 "Processelements".
I would like to know if there is another way to add a CHECK Constraint which checks if there are minimum 2 "Processelements" in this relationship. Maybe a solution with fluent-api or data annotations?
This is used with the Property(() => p).HasDatabaseGeneratedOption() call. Is is perhaps to turn off default DB value generation?
EF uses DatabaseGeneratedOption to figure out what to do with the value of a key column for new entities. If the DatabaseGeneratedOption is Identity EF knows that the value the property is set to can be ignored and that the one that comes from the database should be used. If the DatabaseGeneratedOption is None EF will insert the value of the property to the database as the value of the key column.
In Code First - when Code First conventions find an int property that can be the key property for the given entity they by default will configure this column as identity column (meaning the database will generate the value of the key column/property). DatabaseGeneratedOption.None allows you to overwrite this if you want to set key values on your own.
Its effect is to configure EF to not fetch a new identity value after inserting into the database.
I have a unique key constraint in my SQL Server that is based on two columns (AbsoluteCounter, TimeMfrAudit). If I try to add a list of objects via Entity Framework, how can I check if one of my objects is going to violate this constraint without throwing an exception that will make my entire context.SaveChanges() fail ? I am looking for a best practice here.
Thanks
These would be all objects that violate the unique key constraint:
var violatingObjects = listOfObjectsToAdd
.Where(o => context.Objects.Any(oInDb =>
oInDb.AbsoluteCounter == o.AbsoluteCounter &&
oInDb.TimeMfrAudit == o.TimeMfrAudit))
.ToList();
It is one EXISTS database query per object in the list. If you only want to know the first object that violates the constraint use FirstOrDefault() instead of ToList(). If you only want to know if there is any violating object at all use Any() instead of ToList(). The iteration should stop when the first object has been found.
I have removed the PrimaryKey from my table, refreshed the EDMX, and now I am getting this error message when doing db.SaveChanges():
Unable to update the EntitySet 'Results' because it has a DefiningQuery and no element exists in the element to support the current operation.
Now...
1 - I dont want PrimaryKey in my table. The table is just a bag of values, no PK is required.
2 - I read another post where someone suggested to remove DefiningQuery element from EF generated EDMX. It is not working, and I avoid manual changes to automatically generated EDMX.
Any idea how I can avoid this error, and not define PK in my table?
Thanks.
In Entity Framework everything must have a key, at least in the model. You can remove it from the database but still you'll have to define a key in the model, which may be a composite key to ensure it is unique. Otherwise EF won't be able to materialize or save objects correctly.
However, I would use a primary key in the table anyway. It is no trouble at all to have an identity field in it and you don't have to worry about finding a unique combination of fields yourself. I can't imagine that the table does not need some notion of identity, or can it really have two exactly identical rows?