How to tell EntityFramework 5.0 that there's a one-to-one association between two entities?

让人想犯罪 __ 提交于 2019-12-12 01:56:52

问题


I could go into the EDMX in design view and update the cardinality (1-, 0-, etc.) of associations, but I want to know if it is alright to do that in this scenario.

I have these two tables, let's say:

User
-----
Id


UserProfile
-------------
Id
UserId
Stuff

A single user may have just one profile. Therefore, I have set a UNIQUE constraint no the UserId column in the UserProfile table. Also, UserProfile.Id is defined as a foreign key that references User.Id.

However, in the Entity Framework model, I get the following:

class User
{
  ICollection<UserProfile> UserProfiles { get; set; }
}

At first, I had the UserProfile table without any primary key of its own like this:

UserProfile
--------------
UserId
Stuff

But EntityFramework made that read-only as it needed to have a primary key on every table that you want to be made writable. So, I put an Id column in the UserProfile table as well.

UPDATE

I tried setting the multiplicit/cardinality of the association between the User table and the UserProfile table in my EDMX in the designer. However, I get this error suggesting I should turn it back to what it was, i.e. a one-to-many relationship.

Running transformation: Multiplicity is not valid in Role 'UserBasicProfile' 
in relationship 'FK_UserBasicProfile_User'. Because the Dependent Role 
properties are not the key properties, the upper bound of the multiplicity 
of the Dependent Role must be *.

回答1:


I've found a way. Well, not purely a 1-1 relationship but a 1-0..1 relationship was what I was after, which, for all practical purposes is a one-to-one relationship.

If you ever fall into this trap like I described in my question, here's what you do:

1) Remove the Id field from the dependent table, in this case the UserProfile table. Therefore, do not give it a separate primary key.

2) Instead, mark the foreign key in the dependent table as its own primary key. In this case, mark the UserId field itself as the primary key of the UserProfile table.

In addition to these two, I assume, as I outlined in the question that you've got a primary and foreign key relationship between the authority (the User table in this case) and the dependent table (the UserProfile table in this example).

So, you new table structure should look like this:

User
------
Id


UserProfile
-------------
UserId (foreign key, and also the primary key of this UserProfile table)
Stuff

Entity Framework will then recognize this 1-0..1 relationship.



来源:https://stackoverflow.com/questions/24117279/how-to-tell-entityframework-5-0-that-theres-a-one-to-one-association-between-tw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!