小さな WPF アプリケーションがあります。ソリューションには 5 つのプロジェクトがあります。
UI ENTITIES を持つ個別の DOMAIN クラスが必要で、AUTOMAPPER を使用したいと考えています。
ソリューション全体をここからダウンロードできます: TestWPFAutomapper.zip
UI エンティティ (Entities.Destination.cs) を持つドメイン クラス (Domain.Source.cs) は同じ署名を持ちます。
Entities.Destination.cs に他のロジックを入れたいと思います。
namespace DOMAIN
{
public class Source
{
public int Id { get; set; }
public int Position { get; set; }
}
}
using System.ComponentModel;
namespace ENITITIES
{
public class Destination : INotifyPropertyChanged
{
private int _id;
private int _position;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public int Position
{
get { return _position; }
set
{
_position = value;
OnPropertyChanged("Position");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
私のデータは、CodeFirst で Entity Framework を使用して DAL.DataContext から取得されます。ここでは Source クラスを使用しています。
using System.Data.Entity;
using DOMAIN;
namespace DAL
{
public class DataContext : DbContext
{
public DbSet<Source> Sources { get; set; }
}
}
マッピングは BL.MyAppLogic.cs にあります。このクラスには、ObservableCollection であるプロパティ Items があります。
別の項目をソース クラス コレクションの DB に配置した後、更新を取得しますが、宛先は更新されません。
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using AutoMapper;
using DAL;
using DOMAIN;
using ENITITIES;
namespace BL
{
public class MyAppLogic
{
private readonly DataContext _dataContext = new DataContext();
public ObservableCollection<Source> Items { get; set; }
//public ObservableCollection<Destination> Items { get; set; }
public MyAppLogic()
{
Database.SetInitializer(new MyInitializer());
Mapping();
_dataContext.Sources.Load();
Items = _dataContext.Sources.Local;
//Items = Mapper.Map<ObservableCollection<Source>, ObservableCollection<Destination>>(_dataContext.Sources.Local);
}
private void Mapping()
{
Mapper.CreateMap<Source, Destination>().ReverseMap();
// I tried also Mapper.CreateMap<ObservableCollection<Source>, ObservableCollection<Destination>>().ReverseMap();
}
public int GetLastItem()
{
return _dataContext.Database.SqlQuery<int>("select Position from Sources").ToList().LastOrDefault();
}
public void AddNewItem(Destination newItem)
{
_dataContext.Sources.Add(Mapper.Map<Destination, Source>(newItem));
_dataContext.SaveChanges();
}
}
}
私の問題はマッピングではなく、うまく機能しますが、データベースにアイテムを追加または削除した後にコレクションを更新することです。DOMAIN.Source クラスを使用すると、すべてが機能し、コレクションが更新されます。しかし、私が ENTITIES.Destination データを使用している場合、DB からデータが取得され、DB にいくつかの新しいデータを入れることもできますが、ObservableCollection を refresing することはできません。
BL.MyAppLogic.cs の行 (14 & 23) にコメントを付けて、(15 & 24) のコメントを外してみてください。
助けてくれてありがとう。