Cast from one object to another
I am working on a mailing list application where we have the ability to test out test emails to check formatting and stuff before sending out to the full list.
I have the "live" list table and the "test" list tables setup the same. I am using Linq2SQL for data acc开发者_如何学JAVAess from SQL Server 2005.
My thought process to avoid duplicate code is to pass a bool to indicate a test batch. The problem I am running into now is how do I cast my TestEmailList
object to my EmailList
object (which are both defined as being the same).
IQueryable<EmailList> emailAddresses = null;
if (!isTestSend)
{
// Commented out to avoid an "oops"
//emailAddresses = emailRepository.GetAllActiveEmailAddresses(mailingList);
}
else
{
emailAddresses = (IQueryable<EmailList>)testEmailRepository.GetAllActiveEmailAddresses(mailingList);
}
I get the following error message when I try the above code.
Unable to cast object of type 'System.Data.Linq.DataQuery
1[CivicCenterEventEmail.Models.TestEmailList]' to type 'System.Linq.IQueryable
1[CivicCenterEventEmail.Models.EmailList]'.
Also, if there is a better way to do this, please enlighten me.
You can add a select statement to change the data type.
IQueryable<EmailList> emailAddresses = null;
if (!isTestSend)
{
// Commented out to avoid an "oops"
//emailAddresses = emailRepository.GetAllActiveEmailAddresses(mailingList);
}
else
{
emailAddresses = testEmailRepository.GetAllActiveEmailAddresses(mailingList)
.Select(e=> new EmailList
{
EmailListField1 = e.Field1,
EmailListField2 = e.Field2
});
}
In the select part you can match up the fields from you test email type to you regular email type.
You could try a
GetAllActiveEmailAddresses(mailingList).ToList<EmailList>();
@Becuzz got me on the right track, but didn't quite work. What ended up doing was making another object with the same setup as the test list and the live list and filling all of my data into this new object as a List<>.
List<EmailAddressList> emailAddresses = null;
if (!isTestSend)
{
// Commented out to avoid an "oops"
//emailAddresses = emailRepository.GetAllActiveEmailAddresses(mailingList);
}
else
{
emailAddresses = testEmailRepository.GetAllActiveEmailAddresses(mailingList);
}
Then in my Repository object where I have my data layer, I did the following:
public List<EmailAddressList> GetAllActiveEmailAddresses(int groupId)
{
return (from e in db.TestEmailLists
where e.AccountStatus == true && e.GroupId == groupId
select new EmailAddressList
{
EmailId = e.EmailId,
Email = e.Email,
AccountStatus = e.AccountStatus,
ContactName = e.ContactName,
SignupDate = e.SignupDate,
TextOnly = e.TextOnly,
GroupId = e.GroupId
}).ToList();
}
精彩评论