我正在使用实体框架。我想加载一个实体,对其进行编辑,然后将更改保存回数据库中。但无论我编辑的是外键属性还是简单属性,EF 都会给出以下错误:
附加“ClassX”类型的实体失败,因为同一类型的另一个实体已具有相同的主键值。如果图表中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新的,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”。
请注意,这ClassX不是我要更新的类的直接虚拟属性,而是我的类具有导航属性的其他一些类中的虚拟属性。
我读过一些 相关问题。但我真的不知道应该如何将它们应用到我自己的问题上,因为我使用的是下面发布的通用存储库。
public class GenericRepository<T> where T : class
{
private EFDbContext context = new EFDbContext();
public IEnumerable<T> GetAll()
{
return context.Set<T>();
}
public void Insert(T entity)
{
context.Set<T>().Add(entity);
context.SaveChanges();
}
public void Update(T entity)
{
context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
//removed for brevity
}
Run Code Online (Sandbox Code Playgroud)
我遇到了另一个与虚拟属性相关的问题,建议我使用ViewModels对象到对象映射。
据我所知,有3个选择:
ViewModels对象到对象的映射。我不会选择这个,这真的很痛苦,因为 O2O 映射库有很多错误。reference. 但我不能这样做,因为存储库是通用的。也许我应该使用反射 API 来实现这一点?谁能解释一下为什么会出现这个问题以及解决它的最简单方法是什么?
当尝试在本地运行 ASP.NET MVC 应用程序时,一切正常。但是一旦我部署了Azure,它就会不断地给我错误:
无法更新数据库以匹配当前模型,因为存在挂起的更改并且自动迁移被禁用。
因此,我使用 Visual Studio 中的包管理器控制台连接到远程数据库并运行 Update-Database 命令。这给了我同样的错误。当我查看 SQL Server Management Studio 内的数据库时,看起来所有迁移都已应用。
因此,在此之后,我尝试运行 Add-Migration 来查看是否有任何我没有注意到的更改。它创建的迁移与前两个迁移完全相同(其中没有任何内容不属于这些迁移之一)。
到目前为止,该网站运行了大约两周,其中包括一些迁移,运行良好。我不知道如何解决这个问题,因此非常感谢您的帮助。
我确信我正在连接到正确的数据库,因为当我将其更新到目标迁移时,我看到它发生了变化。我也瞄准了正确的项目。
Incorrect usage of spatial/fulltext/hash index and explicit index order我在尝试登录时收到此错误。
我没有使用实体框架迁移。
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public virtual DbSet<Category> Categories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我在 MySQL 中自动生成数据库的代码。我没有迁移文件。
我有简单的上下文类定义:
namespace PowerSupply.Persistance.Facade
{
class PowerSupplyDBContext : DbContext
{
public PowerSupplyDBContext() : base("PowerSupplyDatabase")
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
身体里面什么也没有
public PowerSupplyDBContext() : base("PowerSupplyDatabase")
{
Run Code Online (Sandbox Code Playgroud)
这个空构造函数的目的是什么。这个空的构造函数是如何工作的?
我是 .NET Core 的新手,正在学习 Udemy 课程。我正在尝试启用迁移以代码优先,但我不断收到错误
值不能为空。(参数“连接字符串”)
我做了一些研究,似乎大多数时候文件ConnectionStrings中的拼写错误appsetttings.json。然而,我已经检查了我的所有内容并尝试了几次复制/粘贴以确保我的拼写正确。要么是别的东西,要么是我看得太仔细而忽略了一些东西。
应用程序设置.json
{
"ConnectionStings": {
"DbConnection": "Server=DAVIDPC\\SQLEXPRESS01;Database=dotnet-rpg;Trusted_Connection=true;MultipleActiveResultSets=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Run Code Online (Sandbox Code Playgroud)
启动.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
services.AddControllers();
services.AddAutoMapper(typeof(Startup));
services.AddScoped<ICharacterService, CharacterService>();
}
Run Code Online (Sandbox Code Playgroud) 我有一个 linq 查询,需要 31 秒。这是我第一次收到这么晚的询问,我不知道该怎么办。让我向您展示我的查询:
public IEnumerable<WebFairField> WebFairFieldForFair(Guid ID)
{
return TradeTurkDBContext.WebFairField.Where(x => x.DataGuidID==ID)
.Include(x => x.Category)
//
.Include(x=>x.FairSponsors)
.ThenInclude(x=>x.Company)
.ThenInclude(x=>x.FileRepos)
//
.Include(x=>x.WebFairHalls)
.ThenInclude(x=>x.HallSeatingOrders)
.ThenInclude(x=>x.Company)
.ThenInclude(x=>x.FileRepos)
//
.Include(x=>x.HallExpertComments)
.Include(x=>x.Products)
.Include(x=>x.FairSponsors)
.AsNoTracking().ToList();
}
Run Code Online (Sandbox Code Playgroud)
我确信这是一个正确的查询,但我不知道为什么该查询花费了太多时间。
谢谢你的帮助!!
linq asp.net asp.net-mvc ef-code-first entity-framework-core
对于示例我正在使用此连接字符串:
<connectionStrings>
<add name="PicturesDatabase"
connectionString=" Server=.;
Database=SomeprojectDatabase;
Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
<../>
Run Code Online (Sandbox Code Playgroud)
然后我在Application_Start()中使用它:
Database.DefaultConnectionFactory =
new SqlConnectionFactory(ConfigurationManager.
ConnectionStrings["PicturesDatabase"].ConnectionString);
Run Code Online (Sandbox Code Playgroud)
在我的数据库中,我得到了这个非常奇怪的新数据库: MyAppNamespace.Models.PicturesCatalog, 带有两个表dbo.EdmMetadata和dbo.Pictures
表很好,但为什么不用这些表创建一个名为PicturesDatabase的新数据库(如连接字符串中)?
我试过几次删除这个表,我尝试创建PicturesDatabase并使用它...但它仍然生成这个MyAppNamespace.Models.PicturesCatalog.它有什么问题?我该如何解决?
我的"Bookshelf"测试应用程序中有两个POCO:
/// <summary>
/// Represents a book
/// </summary>
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public virtual Loaner LoanedTo { get; set; }
}
/// <summary>
/// Represents a Loaner
/// </summary>
public class Loaner
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Loans …Run Code Online (Sandbox Code Playgroud) 给定这些类,使用EF 4.1 Code First,这将(按照惯例)留给页面和标记之间的多对多关系:
public interface ITaggable
{
ICollection<Tag> { get; set; }
}
public class Page : ITaggable
{
public virtual ICollection<Tag> { get; set; }
}
public class Tag
{
public virtual ICollection<Page> { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
由于我有一堆其他类,实现ITaggable我必须将所有这些集合添加到Tag:
public class Tag
{
public virtual ICollection<Page> { get; set; }
public virtual ICollection<Post> { get; set; }
public virtual ICollection<Event> { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
如果我在TagEF 上省略这些属性会产生一对多的关系.有没有办法离开了ICollection<T>上Tag并获得了许多一对多的关系呢? …
mapping many-to-many entity-framework ef-code-first entity-framework-4.1
我首先使用Entity Framework代码为我的用户管理数据库后台存储.我有一个"添加用户角色"操作,它将用户从数据库中提取,将该用户添加到该角色,然后保存更改.但是,当我这样做时,用户的新副本将插入到数据库中,其中包含一个新的/不同的ID(唯一键),而不是我从数据库中提取的用户,我不知道为什么.有关为什么会发生这种情况的任何想法?
IEnumerable<long> usersIdsToGiveRole = from u in vm.UsersNotInSelectedRole where u.IsSelected select u.Id; // say, yields "5"
IEnumerable<User> usersToGiveRole = _userRepository.InternalUsers.Where(u => usersIdsToGiveRole.Contains(u.ID)); // gets user with ID 5
foreach (var user in usersToGiveRole)
{
selectedRole.UsersWithRole.Add(user);
}
_roleRepository.SaveChanges(); // creates new user with ID 6 cloning all other fields of user 5
Run Code Online (Sandbox Code Playgroud) ef-code-first ×10
c# ×4
asp.net-mvc ×3
ado.net ×1
asp.net ×1
asp.net-core ×1
constructor ×1
linq ×1
many-to-many ×1
mapping ×1
mysql ×1