gpt4 book ai didi

c# - 最小起订量 - 使用 DbEntityEntry 更新

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

我正在使用 EF6。生成的代码类似于:

public partial class MyDataContext : DbContext
{
public MyDataContext() : base("name=mydata")
{
}

public virtual DbSet<Book> Books { get; set; }
}

然后我有一个通用的存储库,例如:

public class GenericRepository<TObject> where TObject : class
{
protected readonly MyDataContext Context;

protected GenericRepository(MyDataContext context)
{
Context = context;
}

public virtual TObject Update(TObject data, int id)
{
if (data == null)
return null;

TObject obj = Context.Set<TObject>().Find(id);
if (obj != null)
{
Context.Entry(obj).CurrentValues.SetValues(data);
Context.SaveChanges();
}

return obj;
}
}

然后我有一个使用 GenericRepository 来更新数据的服务:

public class MyDataService<TObject> where TObject : class
{
private readonly MyDataContext context;

public MyDataService(MyDataContext ct)
{
context = ct;
}

public TObject Update(TObject obj, int id)
{
var r = new GenericRepository<TObject>(context);
return r.Update(obj, id);
}
}

所以我可以用这样的东西更新一本书:

var ds = new MyDataService<Book>(new MyDataContext());
var data = ds.Update(new Book { Name = "New Name" }, 1);

这工作正常。接下来,我尝试使用 Moq 对上面的代码进行单元测试,例如:

var updatedBook = new Book { Name = "Update Book Name" };

var mockSet = new Mock<DbSet<Book>>();
var mockContext = new Mock<MyDataContext>();
mockContext.Setup(c => c.Books).Returns(mockSet.Object);
mockContext.Setup(c => c.Set<Book>().Find(It.IsAny<object[]>()))
.Returns<object[]>(ids => chips.FirstOrDefault(d => d.Id == (int)ids[0]));

var service = new MyDataService<Book>(mockContext.Object);
var data = service.Update(updatedBook, 1);

但是,我在 Context.Entry(obj).CurrentValues.SetValues(data) 行遇到异常。

如何正确模拟 Update 方法?

最佳答案

你可以为 MyDataService 实现一个接口(interface)来模拟它

public Interface IMyDataService<TObject> where TObject : class
{
TObject Update(TObject obj, int id);
}

public class MyDataService<TObject>:IMyDataService<TObject>
where TObject : class
{
private readonly MyDataContext context;

public MyDataService(MyDataContext ct)
{
context = ct;
}

public TObject Update(TObject obj, int id)
{
var r = new GenericRepository<TObject>(context);
return r.Update(obj, id);
}
}

起订量:

var mockDataService = new  Mock<IMyDataService<Book>>();
mockDataService.Setup(c=> c.Update(It.Any<Book>(),It.Any<int>()).Returns(updatedbook);

关于c# - 最小起订量 - 使用 DbEntityEntry 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983220/

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