Why wont the DataContext collection refresh after insertion?
I've the following BLL class, which provides tools for adding, updating and deleting elements of a specific type in the db:
public class Asset
{
private Data.DicDataContext _db;
public Asset(int assetID)
{
_db = new Data.DicDataContext();
_asset = _db.Assets.First(a => a.id == assetID);
}
public static Asset New(int assetTypeID, int containerID)
{
Asset nAsset;
using (Data.DicDataContext db = new Data.DicDataContext())
{
Data.Asset asset = new Data.Asset();
asset.typeID = assetTypeID;
开发者_如何学C asset.containerID = containerID;
asset.createdDate = DateTime.Now;
Data.User user = (Data.User)db.Users.First(u => u.id == Convert.ToInt32(HttpContext.Current.Session["user"]));
user.Assets.Add(asset);
db.SubmitChanges();
nAsset = new Asset(asset.id);
}
return nAsset;
}
}
The problem arises, when I add a new element to the db with Asset.New(). The element is correctly saved in the db, but when I try to collect the newly added element with the new Asset() contructor, the element isn't found in the sequence.
Any help would be very appreciative!
You need to change your code so it looks like this.
public Asset(int assetID)
{
using (Data.DicDataContext db = new Data.DicDataContext())
{
_asset = db.Assets.First(a => a.id == assetID);
}
}
Please note it is not really a good practice to keep the connection open so take out your reference to the Data.DicDataContext()
this line private Data.DicDataContext _db;
You must have a using
in every method. Just like in your New Method.
精彩评论