【发布时间】:2018-01-10 01:19:07
【问题描述】:
当我查看 asp.net Identity 2 示例时,我发现了一个有趣的点。
这里的重点是使用id列中的Guid。当我到表定义时(例如:AspNetRoles表)我看到了下面的命令:
CREATE TABLE [dbo].[AspNetRoles] (
[Id] NVARCHAR (128) NOT NULL,
[Name] NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED ([Id] ASC)
);
在显示表数据中我看到了 id 的值:
5de2f031-e329-42b8-868e-c402acc18969
真的很喜欢指导
我也去了模型文件夹,看到了 RoleViewModel 模型
public class RoleViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "RoleName")]
public string Name { get; set; }
}
我决定像上面的代码(字符串 Guid)一样更改我的项目中的列
我将模型从 long id 更改为 Guid Id
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Id { get; set; }
但在我的表中定义是:
[Id] UNIQUEIDENTIFIER DEFAULT (newsequentialid()) NOT NULL,
我知道我必须将Guid改为string,但是数据库如何自动将Guid转换为string ? (我的意思是自动增量 sql server 部分或属性函数 [DatabaseGenerated (DatabaseGeneratedOption.Identity)])
另外,下面为Guid编写的代码,也异常遇到:
public bool RegisterUser(RegisterViewModel registerViewModel)
{
try
{
var currentUser = (from u in _allUsers.AsParallel().AsUnordered() where u.EnDecryptedMobileNumber == registerViewModel.MobilePhone select u).FirstOrDefault();
if (currentUser != null)
{
return false;
}
byte[] salt = _hashingClass.GenerateSalt();
byte[] key = _aesCryptography.GenerateRandomNumber(32);
byte[] iv = _aesCryptography.GenerateRandomNumber(16);
User user = new User()
{
Key = key,
Iv = iv,
Salt = salt,
EnDecryptedMobileNumber = registerViewModel.MobilePhone,
EnDecryptedPassword = Convert.ToBase64String(_hashingClass.HashPassword(Encoding.UTF8.GetBytes(registerViewModel.Password), salt, 100000)),
RoleId = Guid.Parse("04B9CE68-61AE-4EC9-A38B-71823DC91026"),
Status = StatusType.Accepted,
RegisterDate = DateTime.Now,
LastEntryDate = DateTime.Now,
Sex = registerViewModel.Sex
};
base.Add(user);
return true;
}
catch (Exception e)
{
return false;
}
}
还有例外:
{"INSERT 语句与 FOREIGN KEY 约束冲突 \"FK_dbo.Users_dbo.Roles_RoleId\"。数据库发生冲突 \"GbDb\",表 \"dbo.Roles\",列 'Id'。语句已 终止。”}
---更新---
我先使用entityframwork代码,我在Configuration.cs文件中初始化了角色:
context.Roles.AddOrUpdate(r => r.Id,
new Role() { Id = Guid.ParseExact("04B9CE68-61AE-4EC9-A38B-71823DC91026", "D"), RoleInSystem = "User", RoleName = "user" },
new Role() { Id = Guid.ParseExact("A79383E3-E22D-46AE-8EE6-E61873315BED", "D"), RoleInSystem = "Coach", RoleName = "coach" },
new Role() { Id = Guid.ParseExact("16BE238F-94B3-4B23-B3A9-10B697707138", "D"), RoleInSystem = "Admin", RoleName = "admin" }
);
(通过visual studio手动创建Guid)
但是当执行 update-database 并运行种子方法时,ids 更改为新值并存储在数据库中! (不知道为什么)
我的问题是如何创建 string-Guid 类型,如身份 2 id 列类型,并为每个记录自动创建?
对于第二个问题,为什么在运行种子方法时将 ids 更改为新的 guid?
【问题讨论】:
标签: c# asp.net sql-server asp.net-identity