EF代码首先绑定到列表框 [英] EF Code First binding to listbox

查看:212
本文介绍了EF代码首先绑定到列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人可以告诉我如何将列表框绑定到实体框架(EF代码第一),我将不胜感激。



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



问题是我的列表框不显示我列出了新添加的Employee对象。应该改变什么来使这项工作?



代码的一些部分:



MainView:

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

MainViewModel:

 命名空间EmployeeViewer.Core.ViewModels 
{
[导出]
[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>员工{get;组; }
// public BindingList< Employee>员工{get;组;

}
}



从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);
}

如果(orderBy!= null)
{
返回orderBy(查询).AsEnumerable(); // ToList();
}
else
{
return query.AsEnumerable(); // ToList();
}
}

通过ICommand(实现为RelayCommand)在另一个区域和视图中,我首先创建并添加一个新的Employee对象到Entity Framework代码。

  public ICommand AddEmployeeCommand 
{
get {return _AddEmployeeCommand; }
}

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


解决方案

搜索 Bing.com 我发现EF有一个本地属性。



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



我向我的GenericRepository添加了一个新的方法:

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

这是最重要的部分:.Local 给你一个与EF!同步的ObservableCollection。



在我的ViewModel中,我这样做:

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

将新的员工添加到EF将导致我的其他视图更新:

  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();
}

解决方案

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!

这篇关于EF代码首先绑定到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆