免責聲明:這是從舊的stackoverflow帖子複製粘貼不再可用,但我已經exaclty相同的問題,所以它似乎適當重新發布它因爲它從來沒有回答過。如何使用自動映射器映射一個數據集與多個表
我有一個存儲過程,將返回填充到數據集中的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(或表)轉換爲reader的示例,這就是我在這裏做的。該方法實際上將第一個表解析爲對象,但不會通過相關表進行枚舉。
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);
}
我覺得好像我錯過在聯繫對象的映射的東西,但我不能找到一個很好的榜樣。
如果我手動填充接觸對象,然後傳遞是我的控制器,它能夠正常使用直接映射
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);
}
就是我想要做的甚至有可能加載ContactModel對象?
我擔心這將是答案,謝謝你的例子! –