我正在尝试使用EF 4 CTP 4更新分离的POCO.
我的域类看起来像这样:
public class User {
public int Id { get; set; }
[Required, DisplayName("First Name")]
public string FirstName { get; set; }
[Required, DisplayName("Last Name")]
public string LastName { get; set; }
[ConcurrencyCheckAttribute, Timestamp]
public byte[] DataVersion { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在存储库中,我有以下内容:
public void SaveUser(User user) {
if (user.Id > 0) {
dbContext.Users.Attach(user);
}
else {
dbContext.Users.Add(user);
}
dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
dbContext继承自DbContext.
我能够做插入很好,但附加不起作用.我运行Sql Profiler,没有为更新发送sql.
我正在使用Entity Framework 4和CTP 4,到目前为止我真的很喜欢它.当我使用Windows身份验证连接到数据库时,我可以正常工作,但当我切换到SQL身份验证时,它失败并显示以下消息.我给了用户一个sysadmin角色,它的默认数据库是master.
错误:
此操作需要连接到"主"数据库.无法创建与"主"数据库的连接,因为已打开原始数据库连接并且已从连接字符串中删除凭据.提供未打开的连接.
有任何想法吗?
......更多错误细节:
[InvalidOperationException: This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection.]
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +344
System.Data.SqlClient.SqlProviderServices.DbDatabaseExists(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +231
System.Data.Objects.ObjectContext.DatabaseExists() +84
System.Data.Entity.Internal.DatabaseOperations.Exists(ObjectContext objectContext) +9
System.Data.Entity.Infrastructure.Database.Exists() +53
System.Data.Entity.Infrastructure.RecreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context) +129
System.Data.Entity.Infrastructure.<>c__DisplayClass2`1.<SetInitializer>b__0(DbContext c) +75
System.Data.Entity.Infrastructure.Database.Initialize() +207
System.Data.Entity.Internal.InternalContext.Initialize() +70
System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext() +9
System.Data.Entity.Internal.InternalContext.TryUpdateEntitySetMappingsForType(Type …Run Code Online (Sandbox Code Playgroud) 在审批工作流程中,我希望确保提醒电子邮件只发送一次.
使用SqlCommand.ExecuteNonQuery,我可以通过测试返回值来确保这一点.使用EF的推荐解决方案是什么?根据文档ObjectContext.SaveChanges不返回等效值.
SqlCommand示例:(在SendMail失败的情况下,TransactionScope用于回滚数据库更新.)
Dim sql = "UPDATE LeaveApprovalRequests SET State = 'Reminded'" &
" WHERE ID=3 AND State <>'Reminded'"
Using scope As New TransactionScope
Using cnx As New SqlConnection(My.Settings.connectionString)
cnx.Open()
Dim cmd As New SqlCommand(sql, cnx)
If 1 = cmd.ExecuteNonQuery Then
SendMail()
End If
scope.Complete()
End Using
End Using
通过启用乐观并发(在RowVersion属性上使用ConcurrencyMode = Fixed)并捕获OptimisticConcurrencyException,我能够识别对象是否实际在商店中更新.现在,TransactionScope(用于在SendMail失败时回滚数据库更新)会引发死锁错误.为什么?
Using scope As New TransactionScope
Using ctx As New ApprovalEntities
Try
Dim approval = ctx.LeaveApprovalRequests.
Where(Function(r) r.ID = 3 And r.State = "Created"
).FirstOrDefault
If approval Is Nothing …Run Code Online (Sandbox Code Playgroud) 有人能指出POCO,自我跟踪实体,POCO代理之间的区别吗?
实际上,我正在使用Entity Framework 4.0和POCO(Repository Pattern),每当我在POCO中做一些更改并调用ObjectContext.Savechanges时,它就会反映到DB.我的问题是,
我正在使用的示例代码,
IEFRepository<Category> catRepository = new EFRepository<Category>();
Category c = catRepository.FindOne<Category>(x => x.Name == "Paper");
c.Name = "Paper";
catRepository.SaveChanges(System.Data.Objects.SaveOptions.None);
Run Code Online (Sandbox Code Playgroud) 当我发布更新查询或其他更改数据库中的数据的数据操作语言(DML)查询时,使用Entity Framework 4,如何查看发送到SQL Server的查询?
假设我做了类似的事情:
someEntityObjectInstance.SomeProperty = newValue;
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
在这种情况下,没有ObjectQuery来执行ToTraceString(),所以我无法真正看到幕后发生了什么.我相信有一些Microsoft SQL Server工具,比如探查器或者可以帮助我查看查询的东西.
另外,我认为VS 2010 Ultimate中的一些Intellitrace会做同样的事情吗?
你能告诉我如何使用SQL 2005 Profiler,如果有这样的事情吗?
更新
我正在查看SQL Server 2005 Profiler中的跟踪,但是当我发出context.DeleteObject()调用或更新对象并调用时context.SaveChanges(),我在Profiler中看不到UPDATE或DELETE查询.我只看到奇怪的SELECT查询.
c# sql-server entity-framework sql-server-2005 entity-framework-4
我正在尝试重新评估我们的n层架构,并希望根据您的经验获得一些建议.这是我们典型的.NET n层(有时是n层)设计.
Project.UI
Project.Services
Project.Business
Project.Model
Project.DataAccess
Run Code Online (Sandbox Code Playgroud)
DataAccess通常由Entity Framework 4和Repository类组成.我试图遵循这个Aggregate Root概念,以避免有一个表的存储库,说起来容易做起来难.我倾向于在存储库和表之间匹配约70%.
模型通常由我的Entity Framework 4实体组成,我一直在使用自我跟踪EF实体成功.
商业是我最挣扎的事情.我通常Manager每个人都有一个班级Repository.此类将包含.Add()等方法,这些方法将在转发到repository.Add()之前执行业务验证.
服务,通常我只会实现这个,但实际上我正在寻找创建基于Web服务的解决方案.该层的任务是在DTO和实体之间编组请求/响应.最重要的是提供更多的coarse grained界面.例如TradingService.SubmitTrade(),它实际上是facade一个业务事务,可能包括AccountManager.ValidateCash(),OrderManager.SubmitOrder()等.
关注
我的业务层是以实体为中心的,实际上它只是实体和存储库之间的粘合剂,两者之间进行了验证.我见过许多设计,其中服务层是对存储库的引用(实质上是跳过"业务层").本质上,它与我的业务层具有相同的目的,它进行验证,但其责任(和命名)是更高级别,更粗粒度的业务事务.使用上面的示例,TradingService.submitTrade()不会委托给任何业务经理类,它本身会查询必要的存储库,执行所有验证等.
我喜欢我的设计,因为我可以在多个服务调用中重用业务层方法,但是我讨厌这样一个事实:对于每个存储库,我都有一个匹配的业务层管理器,创建了大量的额外工作.也许解决方案是业务层级别的不同类型的分组?例如,将各个Manager类(如PhoneManager和EmailManager(请注意我有Phone实体和Email实体))组合到逻辑Manager类(如ContactsManager)中(注意我没有"Contact"实体类型).使用ContactManager.GetPhones()和ContactManager.GetEmail()等方法.
我想,我想知道其他人如何组织和委派职责,无论他们是否有服务层,业务层,两者等等.什么是ORM上下文引用等等.
我有两个项目:
两者都定义Entities.当我尝试执行时
using (var db = new News.Data.Entities("name=Entities"))
{
results1 = db.News.ToList();
}
using (var db = new Tag.Data.Entities("name=Entities"))
{
results2 = db.Tag.ToList();
}
Run Code Online (Sandbox Code Playgroud)
在控制台应用程序上我收到此错误:
指定的架构无效.错误:Model1.csdl(3,4):错误0019:EntityContainer名称必须是唯一的.已定义名为"实体"的EntityContainer.
是否可以使用
News.Data.Entities
Tags.Data.Entities
Run Code Online (Sandbox Code Playgroud)
代替
News.Data.NewsEntities
Tags.Data.TagsEntities
Run Code Online (Sandbox Code Playgroud)
?
我有两张桌子:
RequirementId - PK
FixtureId - PK
RequirementId - FK/NULLABLE /唯一约束
夹具只能有1个要求,其他夹具不应该能够引用相同的要求.夹具不是必须具有要求,它是可选的.
我所做的是,在Sql Server中,我在Fixture表的RequirementId列上放置了一个Unique约束.如何在Entity Framework CTP 5中为此设置映射?
还可以在每个实体上使用双向导航属性吗?
public class Fixture
{
public int FixtureId { get; set; }
public Requirement Requirement { get; set; }
}
public class Requirement
{
public int RequirementId { get; set; }
public Fixture Fixture { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
也许我错了,所以任何建议都会很棒.提前致谢
entity-framework entity-framework-4 ef4-code-only ef-code-first entity-framework-ctp5
我已经构建了一个查询来从两个表中返回数据,在这两个表中,它们通过内连接加入.虽然,因为查询似乎很好,当我尝试从查询中访问选定的字段名称时,我收到错误消息.我如何在此查询中使用.SingleOrDefault()函数.任何人都可以帮我,我该怎么办.
private void FindByPincode(int iPincode)
{
using (ABCEntities ctx = new ABCEntities())
{
var query = from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area};
// var query = ctx.Cities.AsNoTracking().SingleOrDefault(_city => _city.Pincode == iPincode);
if (query != null)
{
cboState.SelectedItem.Text =query.State; //Getting error "Could not found"
cboCity.SelectedItem.Text = query.CityName; //Getting error "Could not found"
txtArea.Text = query.Area; //Getting error "Could not found"
}
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
我最近有理由除了我的存储过程返回的表格数据之外还带回一个值.由于EF不支持具有多个结果集的存储过程,我想我可以通过输出参数完成此操作.但是,使用这种方法我遇到了一个问题,即我只获得了一些数值字段的舍入值.
我的存储过程的参数声明为:
@MyValue numeric(19,6) output
Run Code Online (Sandbox Code Playgroud)
调用映射函数时,我有:
var myValue = new ObjectParameter("MyValue", typeof(decimal));
List<MyResultItem> results = this.ObjectContext.CallMyStoredProc(someId, myValue).ToList();
Run Code Online (Sandbox Code Playgroud)
这总是返回舍入为整数的值(即,刻度为零).
我首先通过手动添加Precision和Scale属性手动编辑底层XML到.edmx来解决这个问题:
<Parameter Name="MyValue" Type="numeric" Mode="InOut" Precision="19" Scale="6" />
Run Code Online (Sandbox Code Playgroud)
不出所料,下次我执行"从数据库更新模型"时,这完全被丢弃了.
我似乎通过更新我的声明来更可靠地修复它ObjectParameter:
var myValue = new ObjectParameter("MyValue", 999999999.999999M);
Run Code Online (Sandbox Code Playgroud)
然而,这似乎非常像一个黑客,我担心未来的问题(即使它只是关于这个神奇数字的维护).是否有更好,更可靠的方法在Entity Framework中使用输出参数?