Auto Mapping errors to individual properties - asp.net-mvc

If I have an auto mapper such as TinyMapper or ExpressMapper configured to map DTOs to Models, and my DTO has notified me that, for example 'myDto.Email' has failed to update, is there a way to map that property back to the model (specifically in my case for ModelState.AddModelError purposes).
Here's a little pseudo code to hopefully clarify my need:
var mapper = SomeMapper.Register<MyModel, MyDto>();
var myDto = mapper.Map(myModel)
var errors = myDto.Update()
if(errors.Any())
{
var error = errors.First();
var property = memberConfiguration.GetMeTheModelPropertyFor(dto => dto.PropertyName= error.Property)
ModelState.AddModelError(property.Name, error.Message);
}
So basically I'm asking which mapper can I achieve something like GetMeTheModelPropertyFor above and how?

Related

getProperty of entity in Odata model in SAPUI5 not working

I have a oData model with entities : Order, OrderInformation. There is 1 : 1 an association between Order and OrderInformation.
Now in the view, based on a value in OrderInformation, I should hide / display a button.
In the controller, following logic to get the value of OrderInformation->appUrl does not work but I can read the property of entity 'Order'.
Init: function(){
// Not working
var prop = this.getView().getModel().getProperty("/OrderInformations('"+ this._orderId + "')/appUrl");
// Working
var prop = this.getView().getModel().getProperty("/Orders('"+ this._orderId + "')/orderType");
}
In transaction /IWFND/GW_CLIENT, following query gives me correct value
/sap/opu/odata/sap/<<ServiceURL>>/OrderInformations('132123')/appUrl
I also tried with the attachRequestCompleted but still no success.
Init:function(){
var oModel = this.getView().getModel();
oModel.attachRequestCompleted(function(oEvent){
var myval = model.getProperty("/OrderInformations('"+ this._orderId + "')/appUrl");
});
}
Can someone provide any idea what can be going wrong ?
BR
Nilesh
You can use the oModel.read function to trigger a request to the backend, within the success handler you read the result of the response and process the received data
var test = oModel.read("OrderInformations('" + this._orderId + "')", {
success: function(oData, response) {
var appUrl = oData.result.appUrl; //response.data.appUrl also works
// do something
},
error: function (oError) {
// Error handling on failed response
}
});
API reference: https://openui5beta.hana.ondemand.com/#docs/api/symbols/sap.ui.model.odata.ODataModel.html#read
I don't understand this line you wrote:
In the controller, following logic to get the value of
OrderInformation->appUrl does not work but I can read the property of
entity 'Order'.
Order is another Entity with a property and the addressing for this works like described above?
Did you init your model like this:
/sap/opu/odata/sap/<<ServiceURL>>/Order? Is OrderInformation a related entity of Order? If yes extend the read with the Navigation property of the odata service which defines the relationship between the two Entities
I hope this answers you question, if anything left, let me know
Best regards

How do I set a property on a breeze entity client-side?

I've tried drilling down into the object and looking at the docs but haven't found anything. I've created an entity and I need to assign some properties manually. I see _backingStore and entityAspect on the object... and I know the property names but don't know how to set them via the breeze entity.
In case it matters, I'm creating a new object and then copying properties over from another object to facilitate cloning.
function createDocument() {
var manager = datacontext.manager;
var ds = datacontext.serviceName;
if (!manager.metadataStore.hasMetadataFor(ds)) {
manager.fetchMetadata(ds).then(function () {
return manager.createEntity("Document");
})
}
else {
return manager.createEntity("Document");
}
}
function cloneDocument(doc) {
var clonedDocument = createDocument();
// Copy Properties Here - how?
saveChanges()
.fail(cloneFailed)
.fin(cloneSucceeded);
}
Not knowing what your properties might be, here are two scenarios -
function cloneDocument(doc) {
var clonedDocument = createDocument();
clonedDocument.docId(doc.docId());
clonedDocument.description(doc.description());
saveChanges()
.fail(cloneFailed)
.fin(cloneSucceeded);
}
There are a few things to note here - I am assuming you are using Knockout and needing to set the properties. If you are not using Knockout then you can remove the parans and use equals -
clonedDocument.docId = doc.docId;
I believe this is true for if you are not using Knockout (vanilla js) and if you are using Angular, but I have not used Breeze with Angular yet so bear with me.
And here's another way that works regardless of model library (Angular or KO)
function cloneDocument(doc) {
var manager = doc.entityAspect.entityManager; // get it from the source
// Check this out! I'm using an object initializer!
var clonedDocument = manager.createEntity("Document", {
description: doc.description,
foo: doc.foo,
bar: doc.bar,
baz: doc.baz
});
return clonedDocument;
}
But beware of this:
clonedDocument.docId = doc.docId; // Probably won't work!
Two entities of the same type in the same manager cannot have the same key.
Extra credit: write a utility that copies the properties of one entity to another without copying entityAspect or the key (the id) and optionally clones the entities of a dependent navigation (e.g., the order line items of an order).

Error copying a record from one entity to another using Entity Framework and Automapper

I am trying to move a record from one table into another matching (almost) table using EF5, MVC, and Automapper.
This code is what I am using:
In My Global Application_Start
//Create Map and manually map StatusCode to Status
Mapper.CreateMap<InstitutionStaging, InstitutionStaging_Archive>()
.ForMember(dest => dest.Status,o =>o.MapFrom(src=>src.StatusCode));
In my Controller
private MyContext db = new MyContext();
Public ActionResult ArchiveMe(int id = 0){
var institutionstaging = db.InstitutionStagings.Find(id);
if (institutionstaging == null)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
var institutionArchive = Mapper.Map<InstitutionStaging, InstitutionStaging_Archive>(institutionstaging);
//Set Archive date to now.
institutionArchive.ArchiveDate = DateTime.Now;
//Error happens on the next line
db.InstitutionStaging_Archives.Add(institutionArchive);
db.InstitutionStagings.Remove(institutionstaging);
db.Entry(institutionArchive).State = EntityState.Added;
//Commit the changes
var result = db.SaveChanges();
}
}
When it hits the line marked "Error happens here==>" I get the following error message.
{"The entity type InstitutionStaging_Archive is not part of the model for the current context."}
The MyContext contains DbSets for both InstitutionStaging and InstitutionStaging_Archive.
Any idea what is happening?
TIA
J
This error isn't typically a problem with AutoMapper, but rather a problem with your Entity Framework model setup.
It can be because you are using the wrong connection string, or it can be because you don't have the model mapped correctly.
Since we don't know what your model is, what your database looks like, or how your mappings are.. can't help much beyond that.
To prove it to yourself, just comment out the automapper stuff and do it by hand, and I'm pretty sure you'll get the same error.

Unit Testing MVC Controllers

A controller in my ASP.NET MVC application pre-populates form data displayed by my view according to a couple of fairly straight forward rules.
It seems like this would be a good thing to cover in my unit testing. But the only way I could see to verify the correct data is placed in the form, would be to extract the logic from the controller in what feels like an unnatural way.
Can someone suggest ways to approach this?
All the examples I've found of unit testing controllers seemed very trivial, such as verifying it returned the expected type of view. I'm not sure I even see the value in that.
You can test by casting the returned object to the appropriate class, instead of using their base class (which is returned by default)
For example, to test the default AccountController you'd so something like this:
var controller = new AccountController();
var result = controller.LogOn() as ViewResult;
var model = result.Model as LogOnModel;
Assert.IsTrue(model.RememberMe); // assuming you "pre-populated" enabled the checkbox
Checking if the returned object is filled with the right data does not seem "unnatural" to me, or did you meant it differently?
I would agree that testing the type of view returned would be somewhat pointless. However, testing that the expected "view" was returned along with its correct data would be a valid test case IMO.
For example here is a singular edit test case for an edit controller. Note, that this example is making use of Moq and Nunit but that aside it's fairly straight forward.
Note, that that ViewResult is cast to the expected view model and the assertions are then made against the expected contact.
Test:
[Test]
public void Edit_Get_Should_Lookup_Contact_From_Repository_And_Return_Edit_View()
{
// arrange
var _repository = new Mock<IContactRepository>();
var expectedContact = new Contact
{
First = "first",
Last = "last",
Email = "mail#test.com"
};
var mockContext = new Mock<ControllerContext>();
_repository.Setup(x => x.GetById(It.IsAny<int>())).Returns(expectedContact);
var controller = new ContactController(_repository.Object)
{
ControllerContext = mockContext.Object
};
// act
var result = controller.Edit(1) as ViewResult;
var resultData = (Contact)result.ViewData.Model;
// assert
Assert.AreEqual("Edit", result.ViewName);
Assert.AreEqual(expectedContact.First, resultData.First);
Assert.AreEqual(expectedContact.Last, resultData.Last);
Assert.AreEqual(expectedContact.Email, resultData.Email);
}
Controller:
[HttpGet]
public ActionResult Edit(int id)
{
var contact = _repository.GetById(id);
return View("Edit", contact);
}

Json and Circular Reference Exception

I have an object which has a circular reference to another object. Given the relationship between these objects this is the right design.
To Illustrate
Machine => Customer => Machine
As is expected I run into an issue when I try to use Json to serialize a machine or customer object. What I am unsure of is how to resolve this issue as I don't want to break the relationship between the Machine and Customer objects. What are the options for resolving this issue?
Edit
Presently I am using Json method provided by the Controller base class. So the serialization I am doing is as basic as:
Json(machineForm);
Update:
Do not try to use NonSerializedAttribute, as the JavaScriptSerializer apparently ignores it.
Instead, use the ScriptIgnoreAttribute in System.Web.Script.Serialization.
public class Machine
{
public string Customer { get; set; }
// Other members
// ...
}
public class Customer
{
[ScriptIgnore]
public Machine Machine { get; set; } // Parent reference?
// Other members
// ...
}
This way, when you toss a Machine into the Json method, it will traverse the relationship from Machine to Customer but will not try to go back from Customer to Machine.
The relationship is still there for your code to do as it pleases with, but the JavaScriptSerializer (used by the Json method) will ignore it.
I'm answering this despite its age because it is the 3rd result (currently) from Google for "json.encode circular reference" and although I don't agree with the answers (completely) above, in that using the ScriptIgnoreAttribute assumes that you won't anywhere in your code want to traverse the relationship in the other direction for some JSON. I don't believe in locking down your model because of one use case.
It did inspire me to use this simple solution.
Since you're working in a View in MVC, you have the Model and you want to simply assign the Model to the ViewData.Model within your controller, go ahead and use a LINQ query within your View to flatten the data nicely removing the offending circular reference for the particular JSON you want like this:
var jsonMachines = from m in machineForm
select new { m.X, m.Y, // other Machine properties you desire
Customer = new { m.Customer.Id, m.Customer.Name, // other Customer properties you desire
}};
return Json(jsonMachines);
Or if the Machine -> Customer relationship is 1..* -> * then try:
var jsonMachines = from m in machineForm
select new { m.X, m.Y, // other machine properties you desire
Customers = new List<Customer>(
(from c in m.Customers
select new Customer()
{
Id = c.Id,
Name = c.Name,
// Other Customer properties you desire
}).Cast<Customer>())
};
return Json(jsonMachines);
Based on txl's answer you have to
disable lazy loading and proxy creation and you can use the normal methods to get your data.
Example:
//Retrieve Items with Json:
public JsonResult Search(string id = "")
{
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
var res = db.Table.Where(a => a.Name.Contains(id)).Take(8);
return Json(res, JsonRequestBehavior.AllowGet);
}
Use to have the same problem. I have created a simple extension method, that "flattens" L2E objects into an IDictionary. An IDictionary is serialized correctly by the JavaScriptSerializer. The resulting Json is the same as directly serializing the object.
Since I limit the level of serialization, circular references are avoided. It also will not include 1->n linked tables (Entitysets).
private static IDictionary<string, object> JsonFlatten(object data, int maxLevel, int currLevel) {
var result = new Dictionary<string, object>();
var myType = data.GetType();
var myAssembly = myType.Assembly;
var props = myType.GetProperties();
foreach (var prop in props) {
// Remove EntityKey etc.
if (prop.Name.StartsWith("Entity")) {
continue;
}
if (prop.Name.EndsWith("Reference")) {
continue;
}
// Do not include lookups to linked tables
Type typeOfProp = prop.PropertyType;
if (typeOfProp.Name.StartsWith("EntityCollection")) {
continue;
}
// If the type is from my assembly == custom type
// include it, but flattened
if (typeOfProp.Assembly == myAssembly) {
if (currLevel < maxLevel) {
result.Add(prop.Name, JsonFlatten(prop.GetValue(data, null), maxLevel, currLevel + 1));
}
} else {
result.Add(prop.Name, prop.GetValue(data, null));
}
}
return result;
}
public static IDictionary<string, object> JsonFlatten(this Controller controller, object data, int maxLevel = 2) {
return JsonFlatten(data, maxLevel, 1);
}
My Action method looks like this:
public JsonResult AsJson(int id) {
var data = Find(id);
var result = this.JsonFlatten(data);
return Json(result, JsonRequestBehavior.AllowGet);
}
In the Entity Framework version 4, there is an option available: ObjectContextOptions.LazyLoadingEnabled
Setting it to false should avoid the 'circular reference' issue. However, you will have to explicitly load the navigation properties that you want to include.
see: http://msdn.microsoft.com/en-us/library/bb896272.aspx
Since, to my knowledge, you cannot serialize object references, but only copies you could try employing a bit of a dirty hack that goes something like this:
Customer should serialize its Machine reference as the machine's id
When you deserialize the json code you can then run a simple function on top of it that transforms those id's into proper references.
You need to decide which is the "root" object. Say the machine is the root, then the customer is a sub-object of machine. When you serialise machine, it will serialise the customer as a sub-object in the JSON, and when the customer is serialised, it will NOT serialise it's back-reference to the machine. When your code deserialises the machine, it will deserialise the machine's customer sub-object and reinstate the back-reference from the customer to the machine.
Most serialisation libraries provide some kind of hook to modify how deserialisation is performed for each class. You'd need to use that hook to modify deserialisation for the machine class to reinstate the backreference in the machine's customer. Exactly what that hook is depends on the JSON library you are using.
I've had the same problem this week as well, and could not use anonymous types because I needed to implement an interface asking for a List<MyType>. After making a diagram showing all relationships with navigability, I found out that MyType had a bidirectional relationship with MyObject which caused this circular reference, since they both saved each other.
After deciding that MyObject did not really need to know MyType, and thereby making it a unidirectional relationship this problem was solved.
What I have done is a bit radical, but I don't need the property, which makes the nasty circular-reference-causing error, so I have set it to null before serializing.
SessionTickets result = GetTicketsSession();
foreach(var r in result.Tickets)
{
r.TicketTypes = null; //those two were creating the problem
r.SelectedTicketType = null;
}
return Json(result);
If you really need your properties, you can create a viewmodel which does not hold circular references, but maybe keeps some Id of the important element, that you could use later for restoring the original value.

Resources