ASP.NET Membership Provider: Defining a foreign key to aspnet_Users.UserName

无人久伴 提交于 2019-12-11 06:49:33

问题


I'd like to setup a foreign key to a default membership table but I'm getting an error when trying to define it. I'm using the default aspnet_Users table and also my own Posts table. I'm trying to setup the tables as follows:

aspnet_Users

  • UserId (PK) uniqueidentifier
  • UserName nvarchar(256)

Posts

  • PostID (PK) int
  • UserName (FK -> aspnet_Users.UserName) nvarchar(256)

However, when I try to set this up using the VS 2010 designer, it gives me the following error:

The columns in table 'aspnet_Users' do not match an existing primary key
or unique constraint.

Is this not working because aspnet_Users.UserName isn't a part of the PK for aspnet_Users? I've tried to change the table to include that as part of the PK (I think that makes it a composite key?) but it's telling me to delete the relationships first before I can do it. Being as I don't know what relationships the default membership tables define, I'd rather find out more before going that route.


回答1:


The error message is fully describing the situation - you're trying to use a non-key field inside a foreign key constraint. You suggest trying to create a composite key to get around this issue, which would work, but why wouldn't you simply use the existing primary key?

The UserID field is a uniqueidentifier PK, so it is already configured for use in a FK. And, you'd be utilizing normalization, so that rather than storing (up to) 256 bytes per Username on each row, you'd only be storing the uniqueidentifier (16 bytes).




回答2:


I think you need to combine it with ApplicationID as well. UserID is not unique except when combined with the application ID.



来源:https://stackoverflow.com/questions/7962217/asp-net-membership-provider-defining-a-foreign-key-to-aspnet-users-username

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