EFCore Add Unique Index using Shadow Property - entity-framework

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.

Related

EF Core - Add Unique Constraint

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:

Perform a Realm Migration that adds primary key

Within Realm how do you perform a Migration that adds the Primary Key function to a property, when using Swift?
This was previously answered for Realm Objective-C here: https://stackoverflow.com/a/29417579/599344
Essentially, if you're promoting a property to a primary key, and the property already has a unique value per object, you don't need to do anything special aside from running a normal migration.
If your new primary key property does have duplicate entries, then you'll need to change their values to something unique inside the migration block.

Violation of unique key constraint while inserting row using EF 4

My object which I am going to insert has a parent object as a navigational property.
When I "add" the object to insert it, it also set the ObjectStateManager of my parent object (which is already inserted) to Added and try to insert it. I've verified it in SQL Profiler and thus raises the exception of unique key violation.
I am getting rid of this in two ways
Before adding the object I set all the navigational properties to null
Set the ObjectStateManager of parent object to Modified.
But this seems more like hack than a solution. I believe Entity Framework must have some elegant solution to this.
Kindly suggest.
The second approach is correct solution for this problem. When you call AddObject EF will attach all entities from the object graph in Added state. If you also have existing entities in the graph you must tell EF about them by either setting their state to Unchanged or Modified.

How to Use inheritance in EF

I am using EF 4.0 , i have one problem
Table structure in DB is:
Table: Setting--->
Name (PK)
GroupBy
DataType
Table: UserSetting-->
SettingName(PK)(FK)
UserName(PK)(FK)
Value
Table: WorkstationSetting-->
SettingName(PK)(FK)
WorkstationName(PK)(FK)
Value
Now i want to make use of inheritance, because WorkstationSetting and UserSetting inherits settings so any suggestion how to achieve inheritance, i tried but i got error like
"Error 39 Error 3003: Problem in mapping fragments starting at line 1621:All the key properties (Settings.Name) of the EntitySet Settings must be mapped to all the key properties (WorkstationSetting.SettingName, WorkstationSetting.WorkstationName) of table WorkstationSetting.
I see you have in UserSetting and WorkstationSetting a composite PK.
If UserSetting and WorkstationSetting are derived from Setting, they should have Name as PK.
Another comment; in general, it's not recommended to use a name or something "meaningful" as PK since it is less scalable and might cause limitations (i.e. max index size). Use instead an int or uniqueidentifier.
I recommend you to introduce a new field which is SettingId which should be added to all three tables. In EF designer, just add the Inheritance.
Look into table per type inheritance. For example look here. It should help you get started. The idea is that you have a table for each concrete type (as you have) and you map it to an object hierarchy.
Maybe your problem is with the keys. How is your mapping defined? Are the associations between the tables defined in the DB?

Entity framework - "Problem in mapping fragments"-error. Help me understand the explanations of this error

Error 3007: Problem in Mapping Fragments starting at lines 186, 205: Non-Primary-Key column(s) [WheelID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.
I found several places on the web describing this error, but I simply don't understand them. (confused smiley goes here)
One
Two
Three
Four
There is something pretty fundamental here, I must be missing. Can you explain it, so that I understand it? Maybe using my real life example below?
Foreign key 1:N Wheels.Id -> Slices.WheelId
I add them to entity framework, and WheelId is not visible in the Slices-entity.
Doing some workaround (deleting the relationship from the db before adding tables to EF - then re-creating it and updating EF) I managed to get the WheelId to stay in Slices, but then I get the error mentioned at the top.
Since Slices.WheelId is an FK, you cannot expose it in your client model, period. There are ways to get the value, though.
var wheelId = someSlice.Wheels.ID;
Update In EF 4 you can do this by using FK Associations instead of independent associations.
Try to remove foreign property column from Entity set using entity model design it will solve your problem
For example
We have two tables one is customer and other one is order, using entity model design we added association between customers and orders when we do this Ado.net entity framework i will add navigation properties to both below tables.
Like
Customer.Orders - Here order is list
Order.Customer
One - Many relation.
So we need to remove property from with name CustomerId[Foreign key column] from Order entity set.
For reference:
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2823634f-9dd1-4547-93b5-17bb8a882ac2/
I was able to overcome this problem by the following steps:
right click the designer window
Select 'update model from database'
Select Add AND make sure that the 'Include foreign key columns in the model' checkbox is selected.
click on Finish...
I had set foreign keys up in the database but framework still wasn't pulling them in correctly. So I tried to add the association myself. 
However, when I did this I would get a mapping error. It took me A WHILE but I figured out. What I did was set up the association using the entity toolbox association tool and then you have to double click on the association (1 to many) line and set the primary and foreign key there. Hopefully, this to help others who might have the same problem. I couldn't find the answer anywhere.
I had this problem for quite a different reason, and the message was slightly different; it didn't say "data inconsistency is possible because the corresponding conceptual side properties can be independently modified."
I have a table involved in my model with a binary column where I store image data. I only want this data returned when I need it (performance is a feature), so I split the table using a method similar to this. Later on, I added a property to that table, then updated the model from the database. The wizard added the property to both entity types that refer to the table with the added property. I had to delete it from one of them to solve the error.
I've had this happen because Entity Framework Update wizard mismapped some keys (or did not update?). As a result, some columns were mistakenly labeled as keys, while actual key columns were treated as plain columns.
The solution was to manually open EDMX file, find the entities, and update the keys.
Couldn't get any of the answer to work with EF6. The problem seems to be the framework doesn't import the foreign keys correctly as Associations. My solution was removing foreign keys from the tables, and then manually adding the associations using Entity Framework model, using the following steps: Entity Framework - Add Navigation Property Manually
For LinQ to Entities queries in EF1, my workaround for not having access to the foreign key as a property is with the following code, which does not produce a join query to the associated table:
dbContext.Table1s.FirstOrDefault(c => (int?)c.Table2.Id == null)
i.e, the generated SQL is:
...WHERE ([Extent1].[Table2Id] IS NULL)...
Solution is to allow deleting Rule = Cascade on Sql association.
Same thing as to be done on .edmx model, adding element to
association:
<Association Name="FK_Wheels_Slices">
<End Role="Wheels" Type= "your tipe here" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
</Association>
I had a table already mapped in EF. I added two more tables which had foreign keys in the previously added table. I then got the 3007 error.
To fix the error I deleted all three tables from the EDMX file, and then re-added them all at once together (via "Update Model from Database..."), instead of in stages.
I checked my Error List window and noticed I had errors in the model. Fixed them and all is well
in my case I solved this error by tick (include foreign key columns in the model)
- update Model from database
- tick (include foreign key columns in the model)
- finish