EF Code First 绑定到列表框

发布于 2024-12-06 06:57:53 字数 2624 浏览 0 评论 0原文

如果有人能告诉我如何将列表框绑定到实体框架(首先是 EF 代码),我将不胜感激。

我正在使用棱镜和mef。有两种视图,一种带有按钮,另一种带有列表框。 (每个都在自己的棱镜区域中)。 通过单击按钮,我创建一个新的 Employee 对象并通过实体框架将其插入到数据库中。

问题是我的列表框没有向我显示列表中新添加的 Employee 对象。为了使这项工作有效,应该改变什么?

代码的某些部分:

MainView:

    <Grid>
    <StackPanel>
        <TextBlock Text="Hello From MainView (Core Module)" />
        <ListBox ItemsSource="{Binding Employees, Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding FirstName}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</Grid>

MainViewModel:

namespace EmployeeViewer.Core.ViewModels
{
  [Export]
  [PartCreationPolicy(CreationPolicy.NonShared)]
  public class MainViewModel : NotificationObject
  {
    private IUnitOfWork _UnitOfWork;

[ImportingConstructor]
public MainViewModel(IUnitOfWork unitOfWork) // IEventAggregator eventAggregator
{
  this._UnitOfWork = unitOfWork;

  Init();
}

private void Init()
{
  this.Employees = new ObservableCollection<Employee>(_UnitOfWork.EmployeeRepository.Get());
  //this.Employees = new BindingList<Employee>(_UnitOfWork.EmployeeRepository.Get().ToList());
}

public ObservableCollection<Employee> Employees { get; set; }
//public BindingList<Employee> Employees { get; set; }

}

从 GenericRepository 获取方法:

    public virtual IEnumerable<TEntity> Get(
  Expression<Func<TEntity, bool>> filter = null,
  Func<IQueryable<TEntity>,
  IOrderedQueryable<TEntity>> orderBy = null,
  string includeProperties = "")
{
  IQueryable<TEntity> query = _DbSet;

  if (filter != null)
  {
    query = query.Where(filter);
  }

  foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
  {
    query = query.Include(includeProperty);
  }

  if (orderBy != null)
  {
    return orderBy(query).AsEnumerable();//.ToList();
  }
  else
  {
    return query.AsEnumerable();//.ToList();
  }
}

通过另一个区域和视图中的 ICommand(实现为 RelayCommand),我首先创建一个新的 Employee 对象并将其插入到实体框架代码中。

public ICommand AddEmployeeCommand
{
  get { return _AddEmployeeCommand; }
}

private void AddEmployee()
{
  _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" });
  _UnitOfWork.Save();
}

I would appreciate it if somebody could tell me how to bind a listbox to the entity framework (EF code first).

I'm using prism and mef. There are two views, one with a button and another with a listbox. (each in their own prism region).
By clicking the button I create a new Employee object and insert it to the database via the entity framework.

The problem is that my listbox doesn't show me the newly added Employee object in the list. What should be changed to make this work?

Some parts of the code:

MainView:

    <Grid>
    <StackPanel>
        <TextBlock Text="Hello From MainView (Core Module)" />
        <ListBox ItemsSource="{Binding Employees, Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding FirstName}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</Grid>

MainViewModel:

namespace EmployeeViewer.Core.ViewModels
{
  [Export]
  [PartCreationPolicy(CreationPolicy.NonShared)]
  public class MainViewModel : NotificationObject
  {
    private IUnitOfWork _UnitOfWork;

[ImportingConstructor]
public MainViewModel(IUnitOfWork unitOfWork) // IEventAggregator eventAggregator
{
  this._UnitOfWork = unitOfWork;

  Init();
}

private void Init()
{
  this.Employees = new ObservableCollection<Employee>(_UnitOfWork.EmployeeRepository.Get());
  //this.Employees = new BindingList<Employee>(_UnitOfWork.EmployeeRepository.Get().ToList());
}

public ObservableCollection<Employee> Employees { get; set; }
//public BindingList<Employee> Employees { get; set; }

}
}

Get method from GenericRepository:

    public virtual IEnumerable<TEntity> Get(
  Expression<Func<TEntity, bool>> filter = null,
  Func<IQueryable<TEntity>,
  IOrderedQueryable<TEntity>> orderBy = null,
  string includeProperties = "")
{
  IQueryable<TEntity> query = _DbSet;

  if (filter != null)
  {
    query = query.Where(filter);
  }

  foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
  {
    query = query.Include(includeProperty);
  }

  if (orderBy != null)
  {
    return orderBy(query).AsEnumerable();//.ToList();
  }
  else
  {
    return query.AsEnumerable();//.ToList();
  }
}

Via an ICommand (implemented as RelayCommand) in another region and view, I create and insert a new Employee object to the Entity Framework code first.

public ICommand AddEmployeeCommand
{
  get { return _AddEmployeeCommand; }
}

private void AddEmployee()
{
  _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" });
  _UnitOfWork.Save();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌生 2024-12-13 06:57:53

Bing.com 搜索后,我发现 EF 有一个本地 财产。

如果您正在寻找解决方案,这就是我所做的:

我在 GenericRepository 中添加了一个新方法:

public virtual ObservableCollection<TEntity> GetSyncedEntityItems()
{
  return _DbSet.Local;
}

这是最重要的部分:.Local 为您提供了一个与 EF 同步的 ObservableCollection !.

在我的 ViewModel 中,我这样做:

this.Employees = _UnitOfWork.EmployeeRepository.GetSyncedEntityItems();

向 EF 添加新的 Employee 将导致我的其他视图更新:

private void AddEmployee()
{
  _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" });
  _UnitOfWork.Save();
}

我不知道这是否是最好的解决方案,如果有更好的选择,请告诉我!

After searching on Bing.com I found out that EF has a Local property.

In case you are looking for a solution here is what I did:

I added a new Method to my GenericRepository:

public virtual ObservableCollection<TEntity> GetSyncedEntityItems()
{
  return _DbSet.Local;
}

This is the most important part: .Local gives you an ObservableCollection which is in sync with the EF!.

In my ViewModel I do this:

this.Employees = _UnitOfWork.EmployeeRepository.GetSyncedEntityItems();

And adding a new Employee to the EF will cause my other View to update:

private void AddEmployee()
{
  _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" });
  _UnitOfWork.Save();
}

I don't know if this is the best solution, if there are better options, please do let me know!

梦幻的心爱 2024-12-13 06:57:53

您需要触发 INotifyPropertyChanged.PropertyChanged,我认为NotificationObject 将有一个很好的方法来做到这一点。

当您的Employees 属性从null 变为包含项目的列表时,您的View 需要收到通知才能更新。

一旦Employees属性不为空,添加的新项目将自动更新视图(ObservableCollection的b/c)。

You need to fire INotifyPropertyChanged.PropertyChanged, I assume NotificationObject will have a nice way to do that.

When your Employees property goes from null to a list with items, your View needs to be notified so it can update.

Once the Employees property is not null, new items added will automatically update the View (b/c of ObservableCollection).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文