EF, Code First - How to set a custom Guid identity value on insert

回眸只為那壹抹淺笑 提交于 2019-12-05 01:47:15

The simple way for you to do this since it is a GUID is to have one constructor in your class like

public EntityRole()
{
   Id = Guid.NewGuid();
}

and remove The database generated option or change it to DatabaseGeneratedOption.None.

You can mark Id as virtual property. So in you project where you creating fake data you can have internal EntityRole with overriden Id and here you can remove DatabaseGeneratedOption.Identity attribute or change it on DatabaseGeneratedOption.None.

Visual Studio 2017, C#, EntityFramework v6.0 allows you to override with a custom value by passing the value in on creation through your controller. it does not need to be defined in the model bc it is already defined within ApplicationUser.

private string DateGuid()
    {
        string pre = "Ugly Users 😍🤔🤣😂-";
        return pre + Guid.NewGuid();
    }

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]    
public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { Id = DateGuid() };
            var result = await UserManager.CreateAsync(user, model.Password);
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!