我可以手动生成Entity Framework AspNet Identity的UserId吗? [英] Can I generate UserId for Entity Framework AspNet Identity manually?

查看:107
本文介绍了我可以手动生成Entity Framework AspNet Identity的UserId吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要自己生成新的Guid值。目前我创建了这个结构的帮助表:

 (id,aspnet_id)
/ pre>

每当我需要获取用户或用户列表时,我必须加入这两个表。


解决方案

我可以告诉实体框架身份管理器不生成新的Guid,你是对的,guid不是在数据库中生成的。如果你看看表格,你会注意到该字段没有默认值。



除此之外,必须设置Entity Framework数据库值在类的构造函数中。如果没有,数据库的默认值将被覆盖,除了数据库中存在的密钥(autonumbers)和字段,但模型不知道。



所以如果您创建一个新的IdentityUser,Id设置为Guid。但是您可以覆盖该值:

  var appUser = new IdentityUser 
{
UserName = model.Email ,
Email = model.Email,
Id =所需的guid
};
var identityResult = await userManager.CreateAsync(appUser,model.Password);

无论如何添加用户,使用userManager或直接,这将工作。所以答案是,是的,你可以。



作为旁注,您还可以扩展IdentityUser以添加字段:

  public class ApplicationUser:IdentityUser 
{
[必需]
public int aspnet_id {get;组; }

public DateTime? LastLogin {get;组; }
}


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?

解决方案

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; }
}

这篇关于我可以手动生成Entity Framework AspNet Identity的UserId吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆