我的ObservableCollection终于提取了数据,但现在它没有保存编辑。
这是我的代码:
public void FillDataGrid(Guid corporationId)
{
var query = from s in entity.Sources
where s.CorporationId == corporationId
select new SourceItem
{
CorporationId = s.CorporationId,
Description = s.Description,
IsActive = s.IsActive,
Name = s.Name,
SourceId = s.SourceId,
TokenId = s.TokenId
};
SoureItemCollection = new ObservableCollection<SourceItem>(query);
SourceDataGrid.ItemsSource = SoureItemCollection;
SourceDataGrid.Columns[2].Visibility = Visibility.Hidden;
SourceDataGrid.Columns[0].IsReadOnly = true;
SourceDataGrid.Columns[1].IsReadOnly = true;
}
这是我要绑定的类:
public class SourceItem
{
private Guid _corporationId1;
private string _description;
private bool _isActive;
private string _name;
private Guid _sourceId;
private Guid _tokenId;
public Guid CorporationId
{
set
{
_corporationId1 = value;
onPropertyChanged(this, "CorporationId");
}
get { return _corporationId1; }
}
public string Description
{
set
{
_description = value;
onPropertyChanged(this, "Description");
}
get { return _description; }
}
public bool IsActive
{
set
{
_isActive = value;
onPropertyChanged(this, "IsActive");
}
get { return _isActive; }
}
public string Name
{
set
{
_name = value;
onPropertyChanged(this, "NAme");
}
get { return _name; }
}
public Guid SourceId
{
set
{
_sourceId = value;
onPropertyChanged(this, "SourceId");
}
get { return _sourceId; }
}
public Guid TokenId
{
set
{
_tokenId = value;
onPropertyChanged(this, "TokenId");
}
get { return _tokenId; }
}
// Declare the PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;
// OnPropertyChanged will raise the PropertyChanged event passing the
// source property that is being updated.
private void onPropertyChanged(object sender, string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
}
保存:
private void Save_Click(object sender, RoutedEventArgs e)
{
entity.SaveChanges();
}
我想在保存之前将ObservableCollection绑定回实体吗?如果是这样,我该怎么做?
答案 0 :(得分:0)
您已创建数据副本,并且您正在编辑该副本。实体框架上下文完全没有意识到这一点。
您可以使用实体数据对象,而不是使用SourceItem
中的字段。例如:
var query = from s in entity.Sources
where s.CorporationId == corporationId
select new SourceItem(s);
class SourceItem
{
private SourceEntity _model;
public SourceItem(SourceEntity model)
{
_model = model;
}
public Guid CorporationId
{
get { return _mode.CorporationId; }
set
{
_model.CorporationId = value;
OnPropertyChanged(this, "CorporationId");
}
}
}
请注意,这与ObservableCollection
无关。如果要添加或删除集合中的项目,则还需要将其同步到实体模型。您可以使用CollectionChanged
事件。
答案 1 :(得分:0)
看到的问题是表达式“var query = from s in entity.Sources .. select new SourceItem {..} ”你没有检索附加到上下文的实体(实体)但是您已经创建了SourceItem类型的新对象,这些对象无法映射回数据库实体。 你应该做的是你应该更改你的SourceItem类,它直接由entity.Sources对象支持(我猜它应该是它的构造函数参数)。将SourceItem字段委托回相应的Sources字段(双向)。因此,SourceItem将封装Sources对象并使用所有WPF内容装饰它以进行MVVM操作。