实体框架6未更新外键关系

时间:2018-12-08 17:04:57

标签: wpf postgresql entity-framework entity-framework-6

你好,我在这里遇到一个奇怪的问题。我有一个Project模型,该模型具有一个Company模型的外键。问题是,当我附加我的Project属性以更新它时,它会更新除Company之外的所有其他原始字段。

Project模型如下:

public class Project
{
    [Key]
    public int ID { get; set; }

    [Index(IsUnique = true)]
    public string Name { get; set; }

    public virtual Company Company { get; set; }

    public bool ExportProjectName { get; set; }

    public DateTime CreatedAt { get; set; }
}

然后我要做的是,我有一个ProjectsViewModel,可以从数据库中获取所有项目。然后,将它们分别包装在ProjectViewModel中,该Project公开了ProjectsViewModel的某些字段,并且还具有保存方法。我认为ProjectViewModel的实现可能并不那么重要,因此我只粘贴填充var projects = dbcontext.Projects.Include(x => x.Company).ToList().Select(x => new ProjectViewModel(x)); this.ListOfProjects = new ObservableCollection<ProjectViewModel>(projects); 的两行:

ProjectViewModel

然后我有SaveProject。看一下public class ProjectViewModel : INotifyPropertyChanged { private Project _project; public Project Project { get { return _project; } set { _project = value; NotifyPropertyChanged("Project"); } } public int ID { get { return Project.ID; } set { Project.ID = value; NotifyPropertyChanged("ID"); } } public string Name { get { return Project.Name; } set { Project.Name = value; NotifyPropertyChanged("Name"); } } public Company Company { get { return Project.Company; } set { Project.Company = value; NotifyPropertyChanged("Company"); } } public ProjectViewModel(Project project) { this.Project = project; } public void SaveProject() { using (DbContext dbcontext = new DbContext()) { // At this state this.Project and this.Company exist in the database dbcontext.Companies.Attach(this.Company); dbcontext.Projects.Attach(this.Project); dbcontext.Entry(this.Project).State = EntityState.Modified; dbcontext.SaveChanges(); } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(String info) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); } } 方法:

SaveProject

就是这样。我将Opened connection at 08/12/2018 17:47:21 +01:00 Started transaction at 08/12/2018 17:47:21 +01:00 UPDATE "public"."Projects" SET "Name"=@p_0,"ExportProjectName"=@p_1,"CreatedAt"=@p_2 WHERE "ID" = @p_3 绑定到了一个刚刚触发的命令。

然后在日志中,我只能看到这样的查询:

dbcontext.Companies.Attach(this.Company);
var p = dbcontext.Projects.Single(x => x.ID == this.ID);
p.Name = this.Name;
p.Company = this.Company;
dbcontext.SaveChanges();

因此,除了公司以外,所有财产都在那里。如果那很重要-我正在将PostgreSQL与NpgSql一起使用。关于相关对象本身未更新,我看到了很多关于SO的问题,但是我找不到任何关系仅会中断的问题。希望有人能帮忙!

编辑: 顺便说一句,下面的代码可以工作,但是我不想自己分配所有属性,并且希望避免再次从数据库获取对象。而且我想知道,为什么这种关系在第一种情况下不会更新,因为这对我来说没有意义。

{{1}}

0 个答案:

没有答案