[英]Entity framework not saving record to join table
My Entity Models. 我的实体模型。 Its DB first approach.
它的数据库优先方法。
public partial class Provider
{
public Provider()
{
this.ProviderSubCatetogryOnes = new HashSet<ProviderSubCatetogryOne>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProviderSubCatetogryOne> ProviderSubCatetogryOnes { get; set; }
}
public partial class SubCategoryOne
{
public SubCategoryOne()
{
}
public int Id { get; set; }
public string Name { get; set; }
}
public partial class ProviderSubCatetogryOne
{
public int Id { get; set; }
public int ProviderId { get; set; }
public int SubCategoryOneId { get; set; }
public virtual Provider Provider { get; set; }
public virtual SubCategoryOne SubCategoryOne { get; set; }
}
I have Providers and Categories. 我有提供者和类别。 I have to update my Provider by selecting some of the categories.
我必须通过选择一些类别来更新我的提供商。
I am trying to do this by the following. 我正在尝试通过以下方式做到这一点。
var provider = GetProvider(); // Returns a Provider Object.
provider.SubCategoryOnes.Add(new ProviderSubCategoryOne()
{
SubCategoryOneId = childCategoryId // existing category id.
});
But when I try to save provider, my join table is not populating with any records. 但是,当我尝试保存提供程序时,我的联接表中没有任何记录。
Following is the code I am using for save. 以下是我用于保存的代码。
public virtual void Update(TDomainModel item)
{
_logger.Info("In Update.");
if (item == null)
throw new ArgumentNullException("item");
try
{
var entity = ToDataEntity(item);
DbEntityEntry dbEntityEntry = Context.Entry(entity);
try
{
if (dbEntityEntry.State == EntityState.Detached)
{
Context.Set<TEntityModel>().Attach(entity);
dbEntityEntry.State = EntityState.Modified;
}
}
catch (InvalidOperationException ex)
{
_logger.Error(ex);
_logger.Info("Trying to update by setting the values to CurrentEntity");
if (item as IUniqueId != null)
{
_logger.Warn("Model is an IUniqueId object. Trying to update by using SetValues.");
TEntityModel oldEntity = CurrentDbSet.Find((item as IUniqueId).Id);
Context.Entry(oldEntity).CurrentValues.SetValues(entity);
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
_savedRecord = entity;
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
public void Save()
{
try
{
_context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
_logger.Error(ex.Message);
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
foreach (DbValidationError validationError in validationResult.ValidationErrors)
{
_logger.Error(validationError.PropertyName+": "+validationError.ErrorMessage);
}
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
Any suggestions? 有什么建议么?
Try adding the following: 尝试添加以下内容:
Provider.SaveChanges();
If I remember correctly that saves the changes to the model, also, I used Database First aproach so it might or might not work. 如果我没记错,也可以将更改保存到模型,那么我也使用了Database First方法,因此它可能会起作用,也可能不会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.