免責事項:これは、もう利用できない古いスタックオーバーフローの投稿からのコピーペーストですが、まったく同じ問題があるため、回答がなかったので再投稿するのが適切だと思われました。
データセットに入力される 4 つの結果セット (連絡先、住所、電子メール、電話) を返すストアド プロシージャがあります。AutoMapper を使用して複雑なオブジェクトを作成したいと考えています。
public class Contact
{
public Guid ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Address> Addresses { get; set; }
public List<Phone> Phones { get; set; }
public List<Email> Emails { get; set; }
}
public partial class Address:BaseClass
{
public Guid ContactId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string StateProvince { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class Email
{
public Guid EmailId { get; set; }
public Guid ContactId { get; set; }
public string EmailAddress { get; set; }
}
public class Phone
{
public Guid PhoneId { get; set; }
public Guid ContactId { get; set; }
public string Number { get; set; }
public string Extension { get; set; }
}
データを取得して連絡先のリストを返すメソッドがあります。DataSet が作成されたら、テーブル間の関係を定義します。
CreateDataReader メソッドを使用して DataSet (またはテーブル) をリーダーに変換する多くの例を見つけました。それがここで行っていることです。このメソッドは、実際には最初のテーブルをオブジェクトに解析しますが、関連するテーブルを列挙しません。
public List<Contact> GetContacts()
{
List<Contact> theList = null;
// Get the data
Database _db = DatabaseFactory.CreateDatabase();
DataSet ds = db.ExecuteDataSet(CommandType.StoredProcedure, "GetContacts");
//The dataset should contain 4 tables
if (ds.Tables.Count == 4)
{
//Create the maps
Mapper.CreateMap<IDataReader, Contact>(); // I think I'm missing something here
Mapper.CreateMap<IDataReader, Address>();
Mapper.CreateMap<IDataReader, Email>();
Mapper.CreateMap<IDataReader, Phone>();
//Define the relationships
ds.Relations.Add("ContactAddresses", ds.Tables[0].Columns["ContactId"], ds.Tables[1].Columns["ContactId"]);
ds.Relations.Add("ContactEmails", ds.Tables[0].Columns["ContactId"], ds.Tables[2].Columns["ContactId"]);
ds.Relations.Add("ContactPhones", ds.Tables[0].Columns["ContactId"], ds.Tables[3].Columns["ContactId"]);
IDataReader dr = ds.CreateDataReader();
theList = Mapper.Map<List<Contact>>(dr);
}
return (theList);
}
Contact オブジェクトのマッピングに何かが欠けているように感じますが、従うべき良い例が見つかりません。
連絡先オブジェクトを手動で設定してコントローラーに渡すと、直接マッピングを使用して ContactModel オブジェクトが適切に読み込まれます
public ActionResult Index()
{
//From the ContactController
Mapper.CreateMap<Contact, Models.ContactModel>();
Mapper.CreateMap<Address, Models.AddressModel>();
List<Models.ContactModel> theList = Mapper.Map<List<Contact>, List<Models.ContactModel>>(contacts);
return View(theList);
}
私がやりたいことは可能ですか?