我有一个从db读取数据的MVC页面。同样在页面上我有一些图像链接到/ MyController / Photo,它也对数据库进行了一些读取。现在浏览器“同时”提取照片,所以我注意到有些照片没有显示,我也记录了一些错误:
System.NullReferenceException Object reference not set to an instance of an object.
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
at System.Data.EntityClient.EntityConnection.Open()
......
这是我的代码: 在视图中:
<img src="@Url.Action("Photo", "Profile", new { type = "listing", uID = f.uID })" />
在控制器操作中:
public ActionResult Photo(string type, int uID)
{
User u = null;
if (uID == 0)
u = Repository.repository.GetUserByName(User.Identity.Name);
else
u = Repository.repository.GetUserByID(uID);
if (u != null)
{
...
}
}
我的问题如何将实体框架访问同步到上下文以确保我没有收到这些错误?
答案 0 :(得分:0)
我使用IoC / Dependancy Injection和一个传递到每个存储库的单例DatabaseFactory。 DatabaseFactory类拥有该站点唯一的DbContext,这种方式只有一个,不会遇到任何奇怪的问题。而且我还将我的存储库注入我的控制器......我只是那样懒。
DatabaseFactory
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private CragDbContext _dataContext;
private string _connectionString;
public string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}
public DatabaseFactory(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
_connectionString = connectionString;
}
public CragDbContext Get()
{
if (string.IsNullOrEmpty(_connectionString))
return _dataContext ?? (_dataContext = new CragDbContext());
return _dataContext ?? (_dataContext = new CragDbContext(_connectionString));
}
protected override void DisposeCore()
{
if (_dataContext != null)
_dataContext.Dispose();
}
}
BaseRepository(我所有的存储库都继承自)
public class BaseRepository<T> : IRepository<T> where T : BaseEntity
{
protected CragDbContext DbContext;
protected readonly IDbSet<T> DbSet;
protected IDatabaseFactory DatabaseFactory { get; private set; }
protected CragDbContext Context
{
get { return DbContext ?? (DbContext = DatabaseFactory.Get()); }
}
#region Ctor
public BaseRepository(IDatabaseFactory databaseFactory)
{
if (databaseFactory == null)
throw new ArgumentNullException("databaseFactory");
DatabaseFactory = databaseFactory;
DbSet = Context.Set<T>();
}
#endregion
public virtual void Add(T entity)
{
DbSet.Add(entity);
}
.... etc
}
我实际上在中间有一个UnitOfWork类,但你可以不用它。希望这会有所帮助。