i am trying to implement a log system to the entitiy framework context.
i want to get the deleted element primary key when its state is deleted.
this is my code:
if (item.State == EntityState.Added || item.State == EntityState.Deleted) {
log = new dt_islemLog();
log.eskiDeger = null;
log.islem = (item.State == EntityState.Added) ? Enums.GetDBValue(Enums.islemDurum.EKLENDI) : Enums.GetDBValue(Enums.islemDurum.SILINDI);
log.islemYapanKullanici_id = kullaniciID;
log.nesneAd = item.Entity.GetType().Name;
log.oturum_id = oturumID;
log.zaman = DateTime.Now;
base.SaveChanges();
var ID = GetPrimaryKeyValue(item);
log.nesneID = ID != null ? ID.ToString() : null;
this.dt_islemLog.Add(log);
}
And this is the method that i get the primary key
object GetPrimaryKeyValue(DbEntityEntry entry) {
try {
if (entry.State == EntityState.Detached)
((IObjectContextAdapter)this).ObjectContext.Attach((System.Data.Entity.Core.Objects.DataClasses.IEntityWithKey)entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch(Exception ex) {
return null;
}
}
But i can't attach the (entry.Entitiy) to context because the cast operation is invalid. How can i get the primary key ?
If someone needs i have found the solution. i have updated the primary key method to like this
object GetPrimaryKeyValue(DbEntityEntry entry)
{
try
{
if (entry.State == EntityState.Detached)
this.Set(entry.Entity.GetType()).Attach(entry.Entity);
var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
}
catch
{
return null;
}
}
Related
Hi i have an error when i trying add object to database. Error message is:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
My adding methods:
public void AddProduct(string category, FormCollection formCollection, HttpPostedFileBase image) //Dodaje nowy produkt do bazy.
{
var product = GetNewProduct(category);
var EfContext = GetEfContext(category);
foreach(var property in product.GetType().GetProperties())
{
if(property.Name != "ImageData" && property.Name != "ImageMimeType")
{
var NewValue = Convert.ChangeType(formCollection[property.Name], property.PropertyType);
property.SetValue(product, NewValue);
}
else
{
if (property.Name == "ImageData")
{
property.SetValue(product, new byte[image.ContentLength]);
}
if(property.Name == "ImageMimeType")
{
property.SetValue(product, image.ContentType);
}
if(product.GetType().GetProperty("ImageData").GetValue(product) != null && product.GetType().GetProperty("ImageMimeType").GetValue(product) != null)
{
image.InputStream.Read((byte[])product.GetType().GetProperty("ImageData").GetValue(product), 0, image.ContentLength);
}
}
}
EfContext.GetType().GetMethod("AddProduct").Invoke(EfContext, new object[] { product });
}
And
public void AddProduct(GPU product)
{
product.Product_ID = productContext.items.Count() != 0 ? productContext.items.OrderByDescending(x => x.ProductID).Select(x => x.ProductID).FirstOrDefault() + 1 : 1;
context.GPUs.Add(product);
context.SaveChanges();
}
I have this method:
private List < ReportParameter > ParametrosReporte() {
List < ReportParameter > Parametros = new List < ReportParameter > ();
try {
int ? int_Ejercicio = this.radcmbEjercicio.SelectedItem == null ? 0 : this.radcmbEjercicio.SelectedValue.ToInt();
int ? int_Periodo = this.radcmbPeriodo.SelectedItem == null ? 0 : this.radcmbPeriodo.SelectedValue.ToInt();
int ? int_BSC = this.radcmbBSC.SelectedItem == null ? 0 : this.radcmbBSC.SelectedValue.ToInt();
Parametros.Add(Reportes.ParametrosReporte("pe_Ejercicio", int_Ejercicio.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_Mes", int_Periodo.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_BSC", int_BSC.ToString()));
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
return Parametros;
} catch (Exception ex) {
throw new System.ArgumentException("Error en ParametrosReporte", ex);
}
}
As you can see I have logic to retrieve user who is logged in as:
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
but before retrieve it, I want to call it into Parametros.Add like:
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
But I can´t because UsuarioID is out of scope and it throws me
UsuarioID does not exist in the current context
How can I call it and attach to my Parametros.Add?
You can just create a local variable above your creation of catBSC and then use that in both locations:
var usuarioID = ((Usuario) Session["User"]).UsuarioID
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = usuarioID
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", usuarioID));
You can replace var with the actual type, but I didn't want to make an assumption about what this was in your scenario.
Here is my get by id function that returns first or default row of the user account's table that matches the given town id, I want to return all the rows (users) that are having the given town id.
public HttpResponseMessage Get(string id) {
using(KWSB_dbEntities entities = new KWSB_dbEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
var entity = entities.User_Account.FirstOrDefault(e = > e.Town_Id == id);
if (entity != null) {
return Request.CreateResponse(HttpStatusCode.OK, entity);
} else {
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User_Account with Town id = " + id.ToString() + " not found ");
}
}
}
Isn't it just:
var entity = entities.User_Account.FirstOrDefault(e = > e.Town_Id == id);
Needs to become
var entity = entities.User_Account.Where(e = > e.Town_Id == id);
Difference being a where clause selects all the matching rows, firstordefault selects only the 1st matching one.
public HttpResponseMessage Get(string id) {
using(KWSB_dbEntities entities = new KWSB_dbEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
entities.Configuration.LazyLoadingEnabled = false;
var entity = entities.User_Account.FirstOrDefault(e = > e.Town_Id == id);
if (entity != null) {
return Request.CreateResponse(HttpStatusCode.OK, entity);
} else {
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User_Account with Town id = " + id.ToString() + " not found ");
}
}
}
We have a requirement that is we need to access onedirve through asp.net/C# and need to get the latest uploaded file..?
Please help me how to solve this type of requirement..?
i tried the following code..
i used following namespaces. but didn't work
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Filters;
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Models;
private LiveAuthClient MSAuthClient
{
get
{
if (this.liveAuthClient == null)
{
IDictionary<int, string> secretMap = new Dictionary<int, string>();
secretMap.Add(ClientSecretKey, ClientSecret);
this.liveAuthClient = new LiveAuthClient(ClientId, secretMap, null, this);
}
return this.liveAuthClient;
}
}
private MSAccountStatus MSAccountStatus
{
get
{
if (this.msAccountStatus == Controllers.MSAccountStatus.None)
{
using (UsersContext db = new UsersContext())
{
MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
this.msAccountStatus = msAccount != null ? MSAccountStatus.Connected : MSAccountStatus.NotConnected;
}
}
if (this.msAccountStatus == MSAccountStatus.Connected)
{
LiveConnectSession session = this.MSAuthClient.Session;
if (session == null || session.Expires < DateTimeOffset.UtcNow)
{
this.msAccountStatus = MSAccountStatus.ConnectedWithError;
}
}
return this.msAccountStatus;
}
}
Mates, I am having some logic problem here.
If I set the IsApproved true/false with any other setting, it has it´s value updated in the db.
Altough, When I set a new password all other settings that I am changing togheter with is´nt updated in the server.
Could you help me:
CONTROLLER
public ActionResult EditUser(EditModel model)
{
if (ModelState.IsValid)
{
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}
catch (Exception e)
{
return Content("Usuário não atualizado - Erro: " + e);
}
}
else
{
return Content("Model Inválido");
}
}
I don´t get erros and checking with debug I don´t get anu error...
I am pretty sure it is not the best way but it is working and until I find a better solutions this is working:
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
user = Membership.GetUser(model.UserName);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}