gpt4 book ai didi

c# - System.Data.Entity.ModelConfiguration.ModelValidationException

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:32 24 4
gpt4 key购买 nike

我正在使用代码优先方法,我知道我不应该在我的 Controller 中有这么多代码,无论如何我都会收到这个错误

System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

内部异常就是这个

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces,

这是我的代码

 [HttpPost]
public ActionResult Registration(Models.Users model)
{
if (ModelState.IsValid)
{
using (var Ref_DB = new MainDBContext())
{
var encryptedPassword = CustomLibraries.CustomEncrypt.Encrypt(model.Password);
var user = Ref_DB.Users.Create();//this is where error occours
user.Email = model.Email;
user.Password = encryptedPassword;
user.Country = model.Country;
user.Name = model.Name;
Ref_DB.Users.Add(user);
Ref_DB.SaveChanges();
}
}
else
{
ModelState.AddModelError("", "One or more feilds have been errors");
}
return View();

我意识到我的连接字符串可能是我的连接字符串的问题

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>

.mdf 文件在我的 App_Data 文件夹中

这是我的模型

 public class MainDBContext:DbContext
{
public MainDBContext()
:base("name=DefaultConnection")
{

}
public DbSet<Models.Users> Users { get; set; }
}

这是用户类

 public class Users
{
#region [- Ctor -]
public Users()
{

}
#endregion

[Key]
public int Id { get; set; }

#region [- Email -]
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
#endregion

#region [- PassWord -]
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
#endregion

public string Name { get; set; }

public string Country { get; set; }

}

最佳答案

是的,你的连接字符串是错误的。你必须附加 mdf 文件,就像这样 \MyDatabase.mdf

完整的连接字符串:

<add name="DefaultConnection"  connectionString="Data Source=
(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True" providerName="System.Data.SqlClient"/>

更新:

使用这个:

var user = new Models.Users();

代替这个:

var user = Ref_DB.Users.Create();//this is where error occurs

更新 2:

在您的cmd 提示符 上运行以下命令

sqllocaldb create "v12.0"

您必须像这样更改安装目录:

C:\Program Files\Microsoft SQL Server\120\Tools\Binn>sqllocaldb create "v12.0"

更新 3:

Breaking Changes to LocalDB

关于c# - System.Data.Entity.ModelConfiguration.ModelValidationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com