我想從業務發送給服務對象:Accesing和保存動態對象
public abstract class Notification : AggregateRoot
{
public string Title { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public NotificationType NotificationType { get; set; }
}
public class Alert : Notification
{
public object LinkedObject { get; set; }
public bool WasSeen { get; set; }
}
而且從我的單元測試:
[Theory, AutoNSubstituteData]
public async void Send_NotificationIsAlertTypeDocumentDontExist_DocumentShouldBeCreatedAndNotificationSaved(
IDocumentDbRepository<AlertsDocument> repository,
CampaignAlertsSender sender,
Alert notification
)
{
// Arrange
notification.NotificationType = NotificationType.Alert;
notification.LinkedObject = new
{
MerchantId = Guid.NewGuid()
};
repository.GetItemAsync(Arg.Any<Expression<Func<AlertsDocument, bool>>>()).Returns((Task<AlertsDocument>) null);
// Act
await sender.SendAsync(notification);
// Assert
await repository.Received(1).GetItemAsync(Arg.Any<Expression<Func<AlertsDocument, bool>>>());
await repository.Received(1).CreateItemAsync(Arg.Any<AlertsDocument>());
}
看那linkedobject是object
但我new
使它。併發送到服務。
public override async Task SendAsync(Notification notification)
{
if(notification == null)
throw new ArgumentNullException(nameof(notification));
var alert = notification as Alert;
if(alert == null)
throw new ArgumentException();
var linkedObject = alert.LinkedObject as dynamic;
Guid merchantId = Guid.Parse(linkedObject.MerchantId); // here is problem! linkedObject "object" dont have "MerchantId".
var document = await Repository.GetItemAsync(doc => doc.MerchantId == merchantId);
if (document == null)
{
document = new AlertsDocument
{
MerchantId = merchantId,
Entity = new List<Alert>()
};
document.Entity.Add(alert);
}
}
這是問題! linkedObject「object」不具有「MerchantId」。 但是爲什麼?在調試時,我在linkedObject中看到了值MerchantId。 如何做到這一點?
錯誤:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in mscorlib.dll but was not handled in user code
Additional information: 'object' does not contain a definition for 'MerchantId'
還是同樣的問題。 – Nerf