我有一个文档库站点,想要在编辑文档对象时发送电子邮件,其中包含更改的摘要.
数据库交互是使用DBContext的Code First Entities Framework
这是我到目前为止:
[HttpPost]
public ActionResult Edit(Document document, bool sendEmail, string commentsTextBox)
{
if (ModelState.IsValid)
{
docsDB.Entry(document).State = EntityState.Modified;
foreach (string propertyName in docsDB.Entry(document).OriginalValues.PropertyNames)
{
var OriginalValue = docsDB.Entry(document).OriginalValues.GetValue<object>(propertyName);
var NewValue = docsDB.Entry(document).CurrentValues.GetValue<object>(propertyName);
if (!OriginalValue.Equals(NewValue))
{
//capture the changes
}
}
docsDB.SaveChanges();
if (sendEmail)
{
//sends email
}
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
但是,OriginalValue和NewValue始终相同 - 更新的值.
有什么方法,缺少像写入文件那样的hacky,在POST之前捕获文档的状态?
我在Visual Studio中创建了一个空的C#项目,并添加了一个类。然后,我添加了对System.Data.Entity dll的引用。我将一个类添加到我的项目中,然后如下所示编写了一个DbContext对象。但是,我收到以下错误信息。我还需要引用其他哪些dll才能使用它?
错误1类型或名称空间名称'DbContext'在名称空间'System.Data.Entity'中不存在(您是否缺少程序集引用?)
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Entity;
namespace Budget.Data
{
public class BudgetContext : System.Data.Entity.DbContext
{
}
}
Run Code Online (Sandbox Code Playgroud) 我在实体之间有以下关系.公司1 ---*任命*--- 1名员工
我在单独的数据库中有.net asp成员资格.无论何时创建用户,都可以将其分配给公司,员工或管理员角色.
在我的公司控制器的索引操作中,我检查登录用户的角色.根据角色,我做了不同的linq查询.例如,管理员可以获得所有公司的列表,公司可以获得具有与User.Identity.Name相同的用户名属性(字符串)的公司列表.对于管理员和公司角色,它工作正常.
对于employees角色,我想加载与当前员工相关的所有公司.我很难编写一个执行此工作的linq查询.
我试过了
var companies = db.Companies.Include(c => c.Appointments.Select(a=>a.Employee).Where(e=>e.Username.ToLower() == this.User.Identity.Name.ToLower())).ToList();
Run Code Online (Sandbox Code Playgroud)
我得到这个错误"Include路径表达式必须引用在类型上定义的导航属性.使用虚线路径作为参考导航属性,使用Select运算符作为集合导航属性.参数名称:path"
这是源代码,
CompanyController
[Authorize]
public class CompanyController : Controller
{
private MyDBContext db = new MyDBContext();
//
// GET: /Company/
public ViewResult Index()
{
var viewModel = new CompanyIndexViewModel();
if (Roles.IsUserInRole("administrators")) {
viewModel = new CompanyIndexViewModel { Companies = db.Companies.ToList() };
}
else if (Roles.IsUserInRole("companies")) {
viewModel = new CompanyIndexViewModel { Companies = db.Companies.Where(c => c.Username.ToLower().Equals(this.User.Identity.Name.ToLower())).ToList() };
}
else if (Roles.IsUserInRole("employees")) {
var companies …Run Code Online (Sandbox Code Playgroud) 我编写了一个DbContext扩展来尝试确定存储过程是否存在于其关联的数据库中.
public static bool StoredProcedureExists(this DbContext input, string name)
{
int exists = input.Database.ExecuteSqlCommand(string.Format("SELECT TOP 1 * FROM [sys].[objects] WHERE [type_desc] = 'SQL_STORED_PROCEDURE' AND [name] = '{0}';", name));
//return true; // if it exists, else false
}
Run Code Online (Sandbox Code Playgroud)
问题是:无论存储过程是否name存在,我的exists变量(返回ExecSqlCommand)总是包含'-1'.所以我无法确定存储过程是否在数据库中.
在SQL Server Management Studio中执行生成的查询按预期工作,如果存储过程存在则返回一行,如果不存在则返回没有行.
有没有人对如何实现这一点有任何想法(以编程方式确定存储过程是否与数据库一起存在)?
谢谢Rob
我实际上正在寻找一些帮助来学习设计多个存储库的绳索,这些存储库将使用EF访问同一个数据库.我看过示例代码,其中每个存储库都有自己的私有DBContext,但我对此概念有困难.我对这个项目中的通用接口不感兴趣.
我想要一个Identity基于(授权)的多个接口和其他作业特定的存储库,例如单个应用程序中的类别,项目等,其中继承的接口是可重用的,因此是多个DbContext实例.
在SQL中,您有可以提交或回滚事务的事务,因此在EF中,多个repos会访问相同的(实时)数据吗?也许更好的问题是当我想要一个应用程序继承许多特定于作业的存储库时,我应该如何设计我的DAL.
什么jgauffin的意思是, "确保你的库是100%完全抽象化"
这是什么意思?
这是我想弄清楚的一个简单例子.这种做法合理吗?
public class OneRepo: IRepository, IDisposable
{
private DbContext context = new DbContext();
// Methods and whatnot...
}
Run Code Online (Sandbox Code Playgroud)
然后第二个存储库也需要OneRepo使用相同的数据库连接,但我认为它具有单独的内存单元吗?
public class AnotherRepo: IRepository, IDisposable
{
private DbContext context = new DbContext();
// Methods and whatnot...
}
Run Code Online (Sandbox Code Playgroud)
如果我的问题写得不好,我道歉.我实际上发帖比较新,我不确定自己是否清楚自己.我已经决定我不喜欢通用的repos,并且希望使用Role Interface模式基于授权和/或用户任务创建repos.任何帮助解释将不胜感激!
我在这里找到stackoverflow上的帖子之后设置了我的DbContext模型.
这是目前的设置......
public static class DbContext
{
public static MyDbContext Db
{
get
{
if (!HttpContext.Current.Items.Contains("_db"))
{
HttpContext.Current.Items.Add("_db", new MyDbContext());
}
return HttpContext.Current.Items["_db"] as MyDbContext;
}
}
}
Run Code Online (Sandbox Code Playgroud)
上下文在end_request上的global.asax中处理,如下所示:
void Application_EndRequest(object sender, EventArgs e)
{
var db = (MyDbContext)HttpContext.Current.Items["_db"];
if (db != null)
db.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
这样,在我的系统中,我可以访问Db DbContext.Db.xxxx
到目前为止,一切都在本地运行,但是,我还没有在生产环境中测试过多个用户.
我的顾虑...
我在stackoverflow上阅读了这篇文章,现在让我担心多个用户访问静态上下文可能存在数据问题.这应该关注我还是我的安装方式好吗?
我有一个MVC 5应用程序.我想使用标准的aspnet.identity提供程序来启用用户通过标准\ Account视图登录.但是,我还需要连接到第三方数据库,并且也希望首先使用EF代码.
我从Scott Allen Pluralsight获取的主数据库的上下文.我不知道"ApplicationUser"类为什么或继续从IdentityUser继承,但它在他的视频和我创建的以前的网站中工作.它看起来如下:
namespace ESBAMPortal.DataLayer
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
class PortalContext : IdentityDbContext<ApplicationUser>, ESBAMPortal.DataLayer.IPortalContext
{
public PortalContext()
: base("ESBamPortalConString")
{
this.Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<DomainClasses.Portal> Portal {get; set;}
}
}
Run Code Online (Sandbox Code Playgroud)
第三方数据库的上下文如下:
namespace ESBAMPortal.DataLayer
{
public class ESBContext : DbContext, ESBAMPortal.DataLayer.IESBContext
{
public ESBContext()
: base("ESBExceptionConString")
{
this.Configuration.LazyLoadingEnabled = …Run Code Online (Sandbox Code Playgroud) 我希望能够运行异步调用,如下所示:
[Route("doit"),ResponseType(typeof(MyModel))]
public IHttpResponse PostAsyncCall(MyModel model){
//Code removed for simplicity
Task.Factory.StartNew(() => asyncStuff(model.id);
return OK(model);
}
private void asyncStuff(int id) {
MyModel model = db.MyModels.find(id);
//Do things here. Long call to other webservices/processing of data. Time intensive normally.
User user = db.Users.find(model.userId);
//Do more things. Time intensive normally.
}
Run Code Online (Sandbox Code Playgroud)
但是,当异步方法遇到db.方法时会发生错误:
EntityFramework.dll中出现"System.InvalidOperationException"类型的异常,但未在用户代码中处理
附加信息:由于DbContext已被处理,因此无法完成操作.
使用的上下文在这里:
public class MyContext : DbContext, MyContextInterface
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you …Run Code Online (Sandbox Code Playgroud) 我正在将我的项目从ObjectContext迁移到DbContext,我对这句话有疑问:
var query = db.Inventory.Where("it.IdState in {" + states + "}");
Run Code Online (Sandbox Code Playgroud)
这适用于ObjectContext,但现在我在编译时遇到错误:
Error CS1503 Argument 2: cannot convert from 'string' to 'System.Linq.Expressions.Expression<System.Func<Test.DAL.Inventory, bool>>'
Run Code Online (Sandbox Code Playgroud)
现在似乎不可能做到这一点,我试图公开ObjectContext来做到这一点,但我找不到方法
任何的想法?谢谢!
查看有关如何使用数据库上下文池的示例,我发现它是设计用于ServiceCollection:
var serviceProvider = new ServiceCollection()
.AddDbContextPool<AdventureWorksContext>(options => { //options })
.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)
但是简单注入器呢?是否可以在Simple Injector容器中注册数据库池?
ps我的应用不是ASP.NET MVC,只是DAL
dbcontext ×10
c# ×6
.net ×1
asp.net ×1
asp.net-mvc ×1
edit ×1
ef-core-2.1 ×1
exists ×1
irepository ×1
linq ×1
sql-server ×1
where-clause ×1