如果实体在DbContext之外被更改(是一个分离的实体),我在更新实体方面遇到了一个小问题.如果我附加修改后的实体,则其状态不会被修改.
我的代码看起来像这样:
var specificationToSave = GetSpecificationFromTmpStore(userSessionGuid);
using (var context = DataContextFactory.GetDataContext())
{
// this works for update, if I change the values inside the context while debugging
// but it breaks with new entities
context.Specifications.Attach(specificationToSave);
// this works for insert new entities, modified entities will be saved as new entities
context.Specifications.Add((specificationToSave);)
context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我知道NHibernate,它的方法是SaveOrUpdate.如果更新或插入实体,NHibernate会因为值而决定.
使用EF 4.x以及在DbContext之外修改的实体执行此操作的最佳做法是什么?如何告诉EF该实体处于修改状态?
我正在尝试使用Entity Framework 4,POCO和Code-Only设置项目.
在实体框架中导航属性的类型是否可以作为接口?
我有一个"任务"课程.可以将任务分配给用户或组,每个用户或组由单独的类表示并存储在单独的表中.这些类看起来像这样:
public class User : IAssignable
{
public string Name { get; set; }
public int ID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class Group : IAssignable
{
public string Name { get; set; }
public int ID { get; set; }
public string Manager { get; set; }
public string Department { get; set; }
}
public class Task
{
public …Run Code Online (Sandbox Code Playgroud) 在使用SQLite和NHibernate成功之后,我很高兴使用它来进行Entity Framework Code First测试.
如果您有一些示例连接字符串并设置演示,这将是很好的,并节省一点时间从忙碌的一天.
非常感谢.
编辑:
值得一提的是,在通过EF"数据上下文"应用crud操作时,我在调试期间收到此错误:
无法确定"System.Data.SQLite.SQLiteConnection"类型连接的提供程序名称.
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite"/>
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="DataContext"
connectionString="Data Source=:memory:;Version=3;New=True;"
providerName="System.Data.SQLite"
/>
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
希望EF能够以这种方式与SQLite集成.虽然错误消息令人担忧,但可能并非如此.
我搜索过每一个但是找不到答案......
首先,我使用代码创建了多对多的关系,并且运行良好.每个人可以在多个俱乐部,每个俱乐部可以有多个成员.该ClubPersons表已在DB中创建.
public class Person
{
public int PersonId { get; set; }
public virtual ICollection<Club> Clubs { get; set; }
}
public class Club
{
public int ClubId { get; set; }
public virtual ICollection<Person> Members { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我需要添加俱乐部的创建者,这也是一个人(一对多):
public class Club
{
public int ClubId { get; set; }
public virtual ICollection<Person> Members { get; set; }
public virtual Person Creator { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这样做之后,ClubPersons在数据库表中已经没有了,取而代之的是Club_Id在People表 …
我在以下场景中遇到了db生成问题:
1.cs First.Entities命名空间中的项目实体maped到First_Project表.
namespace First.Entities
{
#region using section
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
using System.Diagnostics.CodeAnalysis;
#endregion
[Table("First_Project")]
public class Project
{
[Key]
public int Id
{
get;
set;
}
[Required]
[MaxLength(1000)]
public string Name
{
get;
set;
}
}
}
Run Code Online (Sandbox Code Playgroud)
2.cs在Second.Entities命名空间中的项目实体maped到Second_Project表.
namespace Second.Entities
{
#region using section
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
using System.Diagnostics.CodeAnalysis;
#endregion
[Table("Second_Project")]
public class Project
{
[Key]
public int Id
{
get;
set;
}
[Required]
[MaxLength(1000)]
public string Name
{
get;
set;
} …Run Code Online (Sandbox Code Playgroud) 好吧,我一直盯着屏幕看了几个小时,不知道为什么我会收到这个错误.我在其他一些项目上使用过Code First,之前没有遇到任何问题...
这是错误:
System.InvalidOperationException was unhandled by user code
Message=The properties expression 'sci => sci.ShoppingCartItemId' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'.
Source=EntityFramework
StackTrace:
at System.Data.Entity.ModelConfiguration.Utilities.ExpressionExtensions.GetSimplePropertyAccessList(LambdaExpression propertyAccessExpression)
at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.HasKey[TKey](Expression`1 keyExpression)
at BillingPlatform.DataLayer.BillingDb.OnModelCreating(DbModelBuilder modelBuilder) in [somepath]\BillingDb.cs:line 57
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
InnerException:
Run Code Online (Sandbox Code Playgroud)
这是抛出错误的代码.第一行:
protected …Run Code Online (Sandbox Code Playgroud) 在EF 4.3文档中说:
默认情况下,使用Code First构建数据库不包括私有,受保护或内部属性.如果您在模型中手动包含这些属性,Code First将忽略这些成员上的任何数据注释.这个问题现已修复,Code First处理数据注释.
我的问题是如何首先使用代码包含受保护的属性,特别是使用流畅的API?
将我的实体框架更新到版本6.0.0-alpha1后,我无法更新数据库.这是我得到的错误:
PM> update-database -verbose
Using StartUp project 'DataCenter'.
Using NuGet project 'DataCenter.Domain'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'datacenter' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).
Upgrading history table.
ALTER TABLE [dbo].[__MigrationHistory] ADD [ContextKey] [nvarchar](512) NOT NULL DEFAULT 'DataCenter.Domain.Migrations.Configuration'
ALTER TABLE [dbo].[__MigrationHistory] DROP CONSTRAINT [PK_dbo.__MigrationHistory]
System.Data.SqlClient.SqlException (0x80131904): 'PK_dbo.__MigrationHistory' is not a constraint.
Could not drop constraint. See previous errors.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, …Run Code Online (Sandbox Code Playgroud) entity-framework code-first ef-migrations entity-framework-6
我有EntityFramework的条目删除问题和同一实体的多对多关系.考虑这个简单的例子:
实体:
public class UserEntity {
// ...
public virtual Collection<UserEntity> Friends { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
流畅的API配置:
modelBuilder.Entity<UserEntity>()
.HasMany(u => u.Friends)
.WithMany()
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("FriendId");
m.ToTable("FriendshipRelation");
});
Run Code Online (Sandbox Code Playgroud)
Cascade Delete在Fluent API中定义?UserEntity例如,删除a的最佳方法是什么Foo?
现在找我,我一定要Clear对Foo的Friends集合,然后我需要加载的所有其他UserEntities,其中包含Foo在Friends,然后取出Foo从每个列表,之前我删除Foo的Users.但这听起来太复杂了.
是否可以直接访问关系表,以便我可以删除这样的条目
// Dummy code
var query = dbCtx.Set("FriendshipRelation").Where(x => x.UserId == Foo.Id || x.FriendId == Foo.Id);
dbCtx.Set("FriendshipRelation").RemoveRange(query);
Run Code Online (Sandbox Code Playgroud)谢谢!
Update01:
我知道这个问题的最佳解决方案是在调用之前执行原始sql语句SaveChanges: …
c# entity-framework code-first ef-code-first entity-framework-6
我正在使用"EntityFramework.Core": "7.0.0-rc1-final"由SQL Server 2012 Express DB支持的Entity-Framework Core(版本)的ASP.NET MVC 6项目.
我需要模拟Person实体和Address实体之间的多对多关系.根据本指南,我使用PersonAddress连接表实体对其进行建模,因为这样我可以存储一些额外的信息.
我的目标是以这种方式设置我的系统:
Person删除PersonAddress实例,则必须删除所有相关实例.Address它们引用的所有实例也必须删除,只要它们与其他PersonAddress实例无关.PersonAddress删除Address实例,则只有与其他PersonAddress实例无关时,才必须删除与其关联的实例.所有Person实例都必须存在.Address删除PersonAddress实例,则必须删除所有相关实例.所有Person实例都必须存在.我认为大多数工作必须在Person和之间的多对多关系中完成Address,但我希望也写一些逻辑.我将把这一部分从这个问题中解脱出来.我感兴趣的是如何配置我的多对多关系.
这是目前的情况.
这是Person实体.请注意,此实体与其他辅助实体之间存在一对多关系.
public class Person
{
public int Id {get; set; } //PK
public virtual ICollection<Telephone> Telephones { get; set; } //navigation property …Run Code Online (Sandbox Code Playgroud) c# entity-framework code-first ef-code-first entity-framework-core