【发布时间】:2015-03-20 15:20:24
【问题描述】:
我使用实体框架设置了 Web Api 2。
我已经创建了一个ActionFilterAttribute,它应该将每次调用都记录到数据库中。
如果一次拨打一个电话,这很好用。但是,如果同时拨打多个电话,它就会失败。对不同类型的并发感到困惑,我会针对我的具体场景提出问题。
如何修改现有代码,以便添加数据库条目而不会发生并发调用冲突?
附带说明:每个日志条目都有一个 ID,应该由数据库生成。
public class AppLogAttribute : ActionFilterAttribute
{
//private AppContext db = new AppContext(); //I can use this or the using statement.
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var ip = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
var userId = Convert.ToInt32(actionContext.RequestContext.Principal.Identity.Name);
var url = actionContext.Request.RequestUri.ToString();
var date = DateTime.Now;
var logEntry = new LogEntry
{
Date = date,
IpAddress = ip,
Url = url,
UserID = userId
};
//Problems here for concurrent calls!
using (var db = new AppContext())
{
db.LogEntries.Add(logEntry);
db.SaveChanges();
}
}
}
LogEntry 类 ...
public class LogEntry
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long ID { get; set; }
public int UserID { get; set; }
public string IpAddress { get; set; }
public DateTime Date { get; set; }
public string Url { get; set; }
}
【问题讨论】:
标签: c# asp.net entity-framework entity-framework-6 asp.net-web-api2