Can I generate UserId for Entity Framework AspNet Identity manually?

守給你的承諾、 提交于 2019-12-12 04:48:28

问题


I need to generate new Guid value myself. Currently I created helper table with this structure:

(id, aspnet_id)

And whenever I need to get a User or list of users, I have to join those two tables.

Can I tell Entity Framework Identity Manager to not generate new Guids but to use generated-by-me value?


回答1:


You are right, the guid is not generated in the database. If you take a look at the table you'll notice that the field doesn't have a default value.

Besides that, with Entity Framework database values have to be set in the constructor of the class. If not, the default value of the database is overwritten, except for keys (autonumbers) and fields that exist in the database but are not known to the model.

So if you create a new IdentityUser, the Id is set with a Guid. But you can overwrite the value:

var appUser = new IdentityUser
{
    UserName = model.Email,
    Email = model.Email,
    Id = "the desired guid"
};
var identityResult = await userManager.CreateAsync(appUser, model.Password);

Regardless how you add the user, using the userManager or directly, this will work. So the answer is, yes you can.

As a sidenote, you can also extend the IdentityUser to add fields:

public class ApplicationUser : IdentityUser
{
    [Required]
    public int aspnet_id{ get; set; }

    public DateTime? LastLogin { get; set; }
}


来源:https://stackoverflow.com/questions/43295183/can-i-generate-userid-for-entity-framework-aspnet-identity-manually

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