Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将Guid.NewGuid添加到SQL数据库问题中_C#_Mysql_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 将Guid.NewGuid添加到SQL数据库问题中

C# 将Guid.NewGuid添加到SQL数据库问题中,c#,mysql,asp.net-mvc,entity-framework,C#,Mysql,Asp.net Mvc,Entity Framework,在数据库的Users表中添加新记录时出现问题。我将ID作为uniqueidentifier,并尝试使用Guid.NewGuid()作为此ID从C#添加新记录 SQL返回错误,该ID不能为空。我试图在数据库中添加具有此生成Guid ID的记录,我看到了相同的错误,但如果我将使用sql NewId添加记录,我会看到该记录已成功添加 我已经使用EF中的代码首先创建了数据库。项目是在ASP.NET MVC 5中创建的 有人能帮我吗 SQL表: CREATE TABLE [dbo].[Users]( [I

在数据库的Users表中添加新记录时出现问题。我将ID作为uniqueidentifier,并尝试使用Guid.NewGuid()作为此ID从C#添加新记录

SQL返回错误,该ID不能为空。我试图在数据库中添加具有此生成Guid ID的记录,我看到了相同的错误,但如果我将使用sql NewId添加记录,我会看到该记录已成功添加

我已经使用EF中的代码首先创建了数据库。项目是在ASP.NET MVC 5中创建的

有人能帮我吗

SQL表:

CREATE TABLE [dbo].[Users](
[Id] [uniqueidentifier] NOT NULL,
[Email] [nvarchar](256) NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[LockoutEndDateUtc] [datetime] NULL,
[UserName] [nvarchar](256) NOT NULL,
 CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
C#代码:

公共类用户:IdentityUser
{
[数据库生成(DatabaseGeneratedOption.Identity)]
公共重写Guid Id{get;set;}
公共用户()
{
Id=Guid.NewGuid();
}
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
}
公共类UserLogin:IdentityUserLogin
{ }
公共类MyRole:IdentityRole
{
}
公共类用户角色:IdentityUserRole
{
}
公共类UserClaim:IdentityUserClaim
{ }
公共类CustomUserStore:UserStore
{
公共CustomUserStore(DbContext上下文):基本(上下文)
{
}
}
公共类CustomRoleStore:RoleStore
{
公共CustomRoleStore(DbContext上下文):基本(上下文)
{
}
}
公共类RecrumentDBContext:IdentityDbContext
{
公共招聘DbContext()
:base(“招聘数据库”)
{
}
公共静态RecrumentDBContext Create()
{
返回新的RecrumentDBContext();
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
modelBuilder.Entity()
.Property(prop=>prop.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity()
.Ignore(col=>col.PhoneNumber)
.Ignore(col=>col.emailconfirm)
.Ignore(col=>col.phonenumberconfirm)
.Ignore(col=>col.twofacturenabled)
.Ignore(col=>col.LockoutEnabled)
.Ignore(col=>col.AccessFailedCount);
modelBuilder.Entity()
.ToTable(“用户”);
modelBuilder.Entity()
.ToTable(“角色”);
modelBuilder.Entity()
.ToTable(“用户角色”);
modelBuilder.Entity()
.ToTable(“用户索赔”);
modelBuilder.Entity()
.ToTable(“用户登录”);
}
}
以及在抛出错误的C#控制器中的注册操作

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    try
    {

        if (ModelState.IsValid)
        {
            var user = new User { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                await _userManager.FindAsync(user.UserName, user.PasswordHash);
                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }
    }
    catch(Exception ex)
    {

    }
    // If we got this far, something failed, redisplay form
    return View(model);
}
[HttpPost]
[异名]
[ValidateAntiForgeryToken]
公共异步任务);
返回重定向到操作(“索引”、“主页”);
}
加法器(结果);
}
}
捕获(例外情况除外)
{
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}
但正如我前面所说的,从C#复制生成的GUID在SQL中插入表查询时会抛出相同的错误

经理:

public class ApplicationUserManager : UserManager<User, Guid>
{
    public ApplicationUserManager(IUserStore<User, Guid> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new CustomUserStore(context.Get<RecruitmentDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<User, Guid>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        //manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        //{
        //    MessageFormat = "Your security code is {0}"
        //});
        //manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        //{
        //    Subject = "Security Code",
        //    BodyFormat = "Your security code is {0}"
        //});
        //manager.EmailService = new EmailService();
        //manager.SmsService = new SmsService();
        //var dataProtectionProvider = options.DataProtectionProvider;
        //if (dataProtectionProvider != null)
        //{
        //    manager.UserTokenProvider = 
        //        new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        //}
        return manager;
    }
}
公共类应用程序管理员:用户管理员
{
公共应用程序服务器管理器(IUserStore存储)
:基地(商店)
{
}
公共静态应用程序SerManager创建(IdentityFactoryOptions选项,IOwinContext上下文)
{
var manager=newapplicationUserManager(newcustomuserstore(context.Get());
//为用户名配置验证逻辑
manager.UserValidator=新的UserValidator(管理器)
{
AllowOnlyAlphanumericUserNames=false,
RequireUniqueEmail=true
};
//配置密码的验证逻辑
manager.PasswordValidator=新密码验证器
{
所需长度=6,
RequiredOnletterDigit=真,
RequireDigit=true,
RequireLowercase=true,
RequireUppercase=true,
};
//配置用户锁定默认值
manager.UserLockoutEnabledByDefault=true;
manager.DefaultAccountLockoutTimeSpan=TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout=5;
//注册双因素身份验证提供商。此应用程序使用电话和电子邮件作为接收验证用户代码的步骤
//您可以编写自己的提供者并将其插入此处。
//manager.RegisterWofactorProvider(“电话代码”,新电话号码提供程序)
//{
//MessageFormat=“您的安全代码为{0}”
//});
//manager.RegisterWofactorProvider(“电子邮件代码”,新的EmailTokenProvider
//{
//Subject=“安全代码”,
//BodyFormat=“您的安全代码为{0}”
//});
//manager.EmailService=新的EmailService();
//manager.SmsService=新的SmsService();
//var dataProtectionProvider=options.dataProtectionProvider;
//if(dataProtectionProvider!=null)
//{
//manager.UserTokenProvider=
//新的DataProtectorTokenProvider(dataProtectionProvider.Create(“ASP.NET标识”);
//}
退货经理;
}
}

从映射器中删除以下行:

modelBuilder.Entity<User>()
            .Property(prop => prop.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

因为您正在将其设置到代码中,并且根据您的表创建SQL查询,这不是数据库的责任。

如果没有代码,将GUID作为主键是一个坏主意,除非它们是特定顺序的,因为这对数据库引擎来说是非常低效的。您确实应该发布最少的代码示例为了说明您所做的工作,可能您没有告诉EF所讨论的属性是PK,或者您已经告诉它应该自动生成PK
modelBuilder.Entity<User>()
            .Property(prop => prop.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]