我在保存我的实体方面遇到了一些问题。我正在为我的wpf应用程序使用mvc模式,并直接将实体绑定到用户界面。
现在我有以下两个类:
public class Extension : DataModelBase
{
private int _extensionId;
private string _extensionName;
private ExtensionGroup _extensionGroup;
private int? _currentExtensionGroupId;
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ExtensionId
{
get
{
return _extensionId;
}
set
{
_extensionId = value;
OnPropertyChanged();
}
}
[Key, Column(Order = 1)]
public string ExtensionName
{
get
{
return _extensionName;
}
set
{
_extensionName = value;
OnPropertyChanged();
}
}
public ExtensionGroup ExtensionGroup
{
get { return _extensionGroup; }
set
{
_extensionGroup = value;
OnPropertyChanged();
}
}
public int? CurrentExtensionGroupId
{
get { return _currentExtensionGroupId; }
set
{
_currentExtensionGroupId = value;
OnPropertyChanged();
}
}
}
public class ExtensionGroup : DataModelBase
{
private string _name;
private ObservableCollection<Extension> _extensions = new ObservableCollection<Extension>();
private int _extensionGroupId;
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ExtensionGroupId
{
get { return _extensionGroupId; }
set
{
_extensionGroupId = value;
OnPropertyChanged();
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
public ObservableCollection<Extension> Extensions
{
get
{
if (_extensions == null)
{
_extensions = new ObservableCollection<Extension>();
}
return _extensions;
}
set
{
_extensions = value;
OnPropertyChanged(nameof(Extensions));
}
}
}
正如您所看到的,每个ExtensionGroup都包含n个Extension。用户可以向扩展组添加扩展,如果他保存组,我希望EF在类Extension中自动添加ExtensionGroup属性。
因此我配置了以下
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ExtensionGroup>()
.HasMany(s => s.Extensions)
.WithOptional(x => x.ExtensionGroup)
.HasForeignKey(x=>x.CurrentExtensionGroupId);
}
那现在该怎么办? 100万小时之后,我现在真的很困惑:D 我认为这是一个问题,我从另一个EF上下文中加载了这些“this.Model.LoadedExtensionGroups”组...
using (var context = new FODataModel())
{
foreach (var extensionGroup in this.Model.LoadedExtensionGroups)
{
//What to do here?
context.SaveChanges();
}
}
在我的尝试中,它出现错误(例如InvalidOperationException:context.Entry(extensionGroup).State = EntityState.Modified;
)
或者他做了重复的作品like this。
我希望有人可以提供帮助。
谢谢!