且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以手动生成Entity Framework AspNet Identity的UserId吗?

更新时间:2023-11-30 21:41:22

我可以告诉实体框架身份管理器不生成新的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; }
}