Artist和之间存在着多对多的关系ArtistType.我可以轻松添加ArtistType如下的艺术家
foreach (var artistType in this._db.ArtistTypes
.Where(artistType => vm.SelectedIds.Contains(artistType.ArtistTypeID)))
{
artist.ArtistTypes.Add(artistType);
}
_db.ArtistDetails.Add(artist);
_db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
这将使用正确的映射更新多对多关联表.但是,当我尝试从表中删除任何项目时,我没有得到任何错误,但它没有从表中删除它?
foreach (var artistType in this._db.ArtistTypes
.Where(at => vm.SelectedIds.Contains(at.ArtistTypeID)))
{
artistDetail.ArtistTypes.Remove(artistType);
}
this._db.Entry(artistDetail).State = EntityState.Modified;
this._db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
public partial class ProcessContext : DbContext
{
static ProcessContext()
{
Database.SetInitializer<ProcessContext>(null);
}
public ProcessContext()
: base("Name=ProcessCS") //Comes from Config File
{
}
--DBSets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
--Code
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个Multi Tenent DB,我们有3个不同的DB.集中式数据库位于公共位置,不会更改.这是存储其余数据库详细信息的位置.我需要创建连接字符串@ runtime,其中详细信息将来自此集中式数据库.有人可以让我知道如何去做吗?
我尝试使用以下代码,但它无法正常工作.此方法将在此处调用
public ProcessContext()
: base(nameOrConnectionString: ConnectionString())
{
}
private static string ConnectionString()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = "XXX";
sqlBuilder.InitialCatalog = "YYY";
sqlBuilder.PersistSecurityInfo = true;
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = "res://*/"; …Run Code Online (Sandbox Code Playgroud) 我有一个带有EF Core 1.1的.NET Core 1.1 API,并使用Microsoft的vanilla设置使用依赖注入为我的服务提供DbContext.(参考:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro#register-the-context-with-dependency-injection)
现在,我正在研究使用WhenAll将数据库读取并行化为优化
所以代替:
var result1 = await _dbContext.TableModel1.FirstOrDefaultAsync(x => x.SomeId == AnId);
var result2 = await _dbContext.TableModel2.FirstOrDefaultAsync(x => x.SomeOtherProp == AProp);
Run Code Online (Sandbox Code Playgroud)
我用:
var repositoryTask1 = _dbContext.TableModel1.FirstOrDefaultAsync(x => x.SomeId == AnId);
var repositoryTask2 = _dbContext.TableModel2.FirstOrDefaultAsync(x => x.SomeOtherProp == AProp);
(var result1, var result2) = await (repositoryTask1, repositoryTask2 ).WhenAll();
Run Code Online (Sandbox Code Playgroud)
这一切都很好,直到我在这些DB Repository访问类之外使用相同的策略,并在我的控制器中使用WhenAll在多个服务中调用这些相同的方法:
var serviceTask1 = _service1.GetSomethingsFromDb(Id);
var serviceTask2 = _service2.GetSomeMoreThingsFromDb(Id);
(var dataForController1, var dataForController2) = await (serviceTask1, serviceTask2).WhenAll();
Run Code Online (Sandbox Code Playgroud)
现在当我从我的控制器调用它时,随机我将得到并发错误,如:
System.InvalidOperationException:ExecuteReader需要一个开放且可用的连接.连接的当前状态已关闭.
我相信的原因是因为有时这些线程会尝试同时访问相同的表.我知道这是EF …
我知道这个问题被问过这么多次.我已阅读并实施了所有解决方案但未获得成功.当我使用EF从数据库检索数据并在View上使用此模型后与模型绑定时,我收到此错误.
我的控制器代码是
using System.Linq;
using System.Web.Mvc;
using JsonRenderingMvcApplication.Models;
namespace JsonRenderingMvcApplication.Controllers
{
public class PublisherController : Controller
{
public ActionResult Index()
{
PublisherModel model = new PublisherModel();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
model.PublisherList = context.Publishers.Select(x =>
new SelectListItem()
{
Text = x.Name,
Value = x.Id.ToString()
}); ;
}
return View(model);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的查看代码是
@model JsonRenderingMvcApplication.Models.PublisherModel
@{
ViewBag.Title = "Index";
}
<div>
@Html.DisplayFor(model=>model.Id)
@Html.DropDownListFor(model => model.Id, Model.PublisherList);
</div>
<div id="booksDiv">
</div>
Run Code Online (Sandbox Code Playgroud)
我的型号代码是
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace …Run Code Online (Sandbox Code Playgroud) 我无法理解的是,是否可以对上下文进行更改并在提交之前在同一事务中获取更改.
这就是我要找的:
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (var context = new DbContext())
{
//first I want to update an item in the context, not to the db
Item thisItem = context.Items.First();
thisItem.Name = "Update name";
context.SaveChanges(); //Save change to this context
//then I want to do a query on the updated item on the current context, not against the db
Item thisUpdatedItem = context.Items.Where(a=>a.Name == "Update name").First();
//do some more query
}
//First here I want it …Run Code Online (Sandbox Code Playgroud) c# transactionscope savechanges dbcontext entity-framework-6
我已经能够DbSet使用此链接模拟来自Moq的实体框架.
但是,我现在想知道如何模拟对SqlQuery的调用.不确定这是否可行或者如何依赖于模拟的db上下文知道正在调用什么"查询".
以下是我想要嘲笑的内容.
var myObjects = DbContext.Database
.SqlQuery<MyObject>("exec [dbo].[my_sproc] {0}", "some_value")
.ToList();
Run Code Online (Sandbox Code Playgroud)
我目前还没有尝试任何东西,因为不知道如何开始嘲笑这个例子.
的嘲讽DbSet是下方再次重申,我可以正确模拟返回DbSet的MyObject的,但现在我试图嘲弄返回列表SQLQuery对MyObject的.
var dbContext = new Mock<MyDbContext>();
dbContext.Setup(m => m.MyObjects).Returns(mockObjects.Object);
dbContext.Setup(m => m.Database.SqlQuery... something along these lines
Run Code Online (Sandbox Code Playgroud) 在MVC Web应用程序中跨多个存储库共享EF DbContext的正确方法是什么?这样做是否谨慎/必要,做或不做的陷阱是什么?
假设:
我似乎在SO和互联网上找到了至少两三个思想流派.
在一个小型网站中,这是一个非问题,这就是为什么大多数MS和社区的例子根本不解决这个问题.
根据我迄今为止的经验,我没有使用有限的存储库.我一直有服务使用DbContext并直接更改它所以我不需要担心这一点.我被告知,从单元测试的角度来看,有限的存储库有很大的好处......我们将看看它是否值得其余部分.
(1)将DbContext共享/范围分配给请求
这很有意思,因为它巧妙地避免了单例上下文的陷阱,一些开发人员认为这是一个答案,但发现DbContext不能以这种方式工作.但它似乎有一个缺点,它假设所有存储库,服务等将在整个请求中协调......通常情况并非如此,对吧?如果一个仓库在另一个仓库完成其工作之前保存了更改,该怎么办 (外(内(内)))
(2)在服务层共享/调整您的DbContext
这对我来说更有意义,因为每个服务应该协调一个特定的工作单元(小写有意).因此,如果在一个请求中使用了多个服务,那么每个服务都有自己的数据库上下文是正确的(如果不是必需的话).
(3)不要共享DbContext,因为它们很便宜
这是我一直这样做的方式......实际上我几乎总是每个请求只有一个DbContext,因为只有一个服务被调用.有时它可能是两个,因为两个服务是由协调工作的控制器调用的.但鉴于我目前的应用程序,有许多有限的存储库,每个存储库都有自己的上下文,这意味着给定的请求可能有3-10个DbContext实例.我认为(可能不正确)这是有问题的.
重复问题:
在MVC Web应用程序中跨多个存储库共享EF DbContext的正确方法是什么?这样做是否谨慎/必要,做或不做的陷阱是什么?
asp.net-mvc repository-pattern service-layer ef-code-first dbcontext
我使用EF4 DbContext为ASP.NET MVC应用程序提供模型.我使用ViewModels为视图和Automapper提供数据,以执行EF POCO和ViewModel之间的映射.Automapper做得很好,但在将ViewModel发回控制器进行更新后,我不清楚使用它的最佳方法.
我的想法是使用ViewModel中包含的密钥获取POCO对象.然后,我想使用Automapper使用ViewModel中的数据更新POCO:
[HttpPost]
public ActionResult Edit(PatientView viewModel)
{
Patient patient = db.Patients.Find(viewModel.Id);
patient = Mapper.Map<ViewModel, Patient>(viewModel, patient);
...
db.SaveChanges();
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
两个问题:
asp.net-mvc viewmodel automapper entity-framework-4 dbcontext
我在单元测试中使用事务来回滚更改.单元测试使用dbcontext,我正在测试的服务使用自己的.它们都包装在一个事务中,一个dbcontext在另一个事务的块中.问题是,当内部dbcontext保存他的更改时,外部dbcontext不可见(我不认为这是因为另一个dbcontext可能已经加载了对象).这是一个例子:
[TestMethod]
public void EditDepartmentTest()
{
using (TransactionScope transaction = new TransactionScope())
{
using (MyDbContext db = new MyDbContext())
{
//Arrange
int departmentId = (from d in db.Departments
where d.Name == "Dep1"
select d.Id).Single();
string newName = "newName",
newCode = "newCode";
//Act
IDepartmentService service = new DepartmentService();
service.EditDepartment(departmentId, newName, newCode);
//Assert
Department department = db.Departments.Find(departmentId);
Assert.AreEqual(newName, department.Name,"Unexpected department name!");
//Exception is thrown because department.Name is "Dep1" instead of "newName"
Assert.AreEqual(newCode, department.Code, "Unexpected department code!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
public class …Run Code Online (Sandbox Code Playgroud) 我在互联网上找不到答案.
假设我有一个DbContext,我只是从中选择所有实体.我不添加,更新或删除任何实体DbSet.
如果我SaveChanges事后打电话给DbSet.它是否真的浪费资源建立连接和其他东西即使我没有做任何改变DbSet?
是否足够智能来检测是否进行了更改,并且行为方式不同?
dbcontext ×10
c# ×6
asp.net-mvc ×3
.net ×2
.net-4.5 ×1
asynchronous ×1
automapper ×1
linq ×1
many-to-many ×1
moq ×1
savechanges ×1
viewmodel ×1