According to the documentation, doing so should retrieve the validators of the given entity:
manager.fetchMetadata().then(function () {
var creditorType = manager.metadataStore.getEntityType("Creditor");
var creditorValidators = creditorType.validators;
});
creditorType.validators is an empty array. I don't understand why because when I inspect dataProperties on creditorType, the validators property is filled for each property.
Should the validators property on the creditorType object not be an aggregate of all the validators properties ?
Not sure where you read that in the documentation but...
Validators on the entityType are typically cross property validations, Validators on a dataProperty or navigationProperty of an entity are specific to a single property. When you 'validate' an entire entity both the 'entityType' and all of the 'dataProperty' and 'navigationProperty' validators are executed. When you change a single property of an entity only the validators for that property are executed.
If you want all of the validators for an entity, this will be the entityType validators + all of the dataProperty validators + all of the navigationProperty validators.
Related
in my project I defined properties in my Ctor
Object.defineProperty(this, 'DTasks', {
get: function() {
return handlePropertyGet('_dtasks', "DTasks");
},
set: function(value) { //used only when loading incidents from the server
handlePropertySet('DTask', value);
},
enumerable: true
});
how ever in the new version of breeze - the addition of use strict really deletes the property so there is a need to add configuralbe: true. But this property is "recreated" in the backingStore and to the value of this property a results field is added. What is the best way to define property in breeze? as this property dont need to be in the backingStore as it isn't mapped one, so maybe to define it in the initialize of the type? As I am working with Microsoft OData which lacks the correct config of the navigation property, I am using those properties for the population of the expand
When you use ES5 Defined Properties for your unmapped properties, Breeze will assume that you want to attach behaviors (such as change tracking, validation, etc) to the setters. This is why Breeze will add the properties to the backingStore. If you want to define them without telling Breeze to track them, you can use the post-construction initializer technique.
var customerInitializer = function(customer) {
customer.isBeingEdited = ko.observable(false);
//or just customer.isBeingEdited = false, if you're using Angular
};
metadataStore.registerEntityTypeCtor('Customer', null, customerInitializer);
You can read more details about the different ways to extend your entities at http://www.breezejs.com/documentation/extending-entities
Hope this helps.
I'm having an ASPNET mvc site hvere the views has viewmodels with knockout. I'm trying to serialize the model passed to the view into the views viewmodel.
The model is passed to the with like standard aspnet mvc
#model Client.Controllers.TripDto
And the knockout viewmodel created using KO mappings is done like
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var viewModel = new TripViewModel();
var mapping = {
'ignore': ["expenses"]
};
ko.mapping.fromJS(mvcModel, mapping, viewModel);
ko.applyBindings(viewModel);
I have a property expenses on the KO "custom" viewmodel. The issue is that this property is not in the MVC model, but just a property that gets its data later.
But so far I haven't been able to pass the model into the viewmodel with out an error
Error: Unable to parse bindings. Message: ReferenceError: expenses is not defined; Bindings value: foreach: expenses
[Break On This Error]
return new Function("$context", "$element", functionBody);
I'm a bit unsure if it really is the mapping that fails, but so far unable to see any uther possible errors.
So the question is, is it possible to use KO mappings where not all propertes are present in the model I'm mapping from?
is it possible to use KO mappings where not all properties are present
in the model I'm mapping from?
I think KO mappings dose not care about this, but the models cares. As you call ko.applyBindings KO 'll search for the property associated with the HTML element, so if you are going to use property in HTML element data-bind='id: property' then this property must exist in your View-Model. But if it was null then it's OK.
Simply you need to extend your view model so include the new property expenses with default value like null
var mapping = {
create: function (options) {
//customize at the root level.
var innerModel = ko.mapping.fromJS(options.data);
innerModel.expenses= null;
return innerModel;
}
}
Kindly check this SO question
I'm implementing a domain tree structure using entity framework + mvc.
I use JSTree to present the org structure.
Note that in that model scheme i use the TypeID property both as a condition of my inheritance and as a property for DomainEntity.
This of corse throw the following error:
Error 3 Error 3032: Problem in mapping fragments starting at line
139:Condition member 'DomainEntities.EntityTypeID' with a condition
other than 'IsNull=False' is mapped. Either remove the condition on
DomainEntities.EntityTypeID or remove it from the mapping.
C:\Code\CamelotShiftManagement\CamelotShiftManagement\Models\CamelotDB.edmx 140 15 CamelotShiftManagement
lets say i will not use TypeID as a property and keep it as a condition for the inheritance association that will result in the following when i'll try to populate a tree of my domain entities:
foreach (var entity in entities)
{
JsTreeModel tree = new JsTreeModel()
{
attr = new JsTreeAttribute()
{
id = entity.EntityID.ToString(),
},
data = entity.EntityName
};
if (entity is OrganizatioanlUnit)
{
tree.attr.type = eNodeType.OrganizationalUnit;
}
if (entity is Calendar)
{
tree.attr.type = eNodeType.Calendar;
}
PopulateTree(entity, tree);
io_Node.children.Add(tree);
}
this code is not maintainable because when a new entity will be introduced i will have to change this code, if i could only access a property that will tell me the type of entity i'm dealing with .. :) .
Here is the dilemma:
If i use inheritances and TypeID as a condition for each inheritance i can not access it as a property of DomainEntity, that will require me to use switch-case against typof(entity) to determine what type i should send to my JSTree plugin because he expects a type identification for each node in his JSON, if i will not use inheritance i will loose the polymorphic capabilities.
It is not only polymorphism i am after.. there will be other methods and properties relevant only for the inherited entities and i can see some injections points in the future...
I'm trying to get server-side validation of an Entity Framework String Property to work. Other server-side validation such as data type validation and required dateTime and numeric EF properties are working.
This in VS 2010, .Net 4.0, MVC2 + Cloud, ADO.Net Entity Framework.
The String Property I am having issues with is mapped to a SQL 2008, Varchar(50) non-nullable column.
When I try to post to my Create action with an empty string for this Property, I get the follwing error.
Exception Details: System.Data.ConstraintException: This property cannot be set to a null value.
When I post to the action with a blank space, I successfully get a required field validation message.
I have tried using Data Annotations and ClientSideValidation but there seems to be issues with ClientSideValidation working on partial views and jquery dialogs.
Here is the orginal autogenerated code from the entity framework.
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String GradeTypeName
{
get
{
return GradeTypeName;
}
set
{
OnGradeTypeNameChanging(value);
ReportPropertyChanging("GradeTypeName");
_GradeTypeName = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("GradeTypeName");
OnGradeTypeNameChanged();
}
}
Depending on the signature of the Action method (CREATE or EDIT), the exception can occur before stepping into the method or within the method when UpdateModel() is called. The inner exception is at the line below from the model.designer.cs file.
_GradeTypeName = StructuralObject.SetValidValue(value, false);
I have been able to reproduce this on a simple mvc2 web application.
i was having the same problem for a while. I have found a piece of explanation here: http://mvcmusicstore.codeplex.com/workitem/6604 . To put it in a nutshell, the exception "System.Data.ConstraintException: This property cannot be set to a null value" is thrown by Entity's Property Validation. This validation is performed when your mvc application tries to bind the form field to the corresponding entity property( it's called PreBinding Validation, and it occurs when submitting the form). As the field is empty( therefore convert to null), the binder tries to bind a null value to the property, which violates the Non-Null constraint on your entity's property.
But if you post with a blank field ( that is different from empty, therefore null) Entity validation passes( as the property is not set to a null value anymore), and then your see the message from the "Required" annotation validation, that is performed after the prebinding (it's PostBinding Validation).
A workaround is to use the annotation [DisplayFormat(ConvertEmptyStringToNull = false)] that tells to the binder not to convert an empty string to null.
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string YourStringProperty { get; set;}
Hope, this helps!
This was very helpful. I'm using MVC3 and entity framework. I was passing my entities directly into the controller, but got the same error when the form was blank. With entity framework you can do data validation by editing the auto-generated code, but creating a separate partial class of the entity worked better for me.
[MetadataType(typeof(TestEntityValidation))]
public partial class TestEntity{
}
public class TestEntityValidation{
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public String name { get;set}
}
Sometimes in database first approach in EF, may you update your column from not null to can be null using SQL query and use 'Update Model From Database...' (in EDMX right click) then maybe property of that entity not updated properly and so if you have some null data in that column ,in mapping ,violation occurs and this error shown.
To fix this; You can check the Nullable in Properties of that property of entity that you updated it.
I've got a number of tables in my db that share common cols: modified by, modified date, etc. Not every table has these cols. We're using LINQ to Enties to generate the
I'd like to create a custom binder class that can handle the automatic binding of these fields. Is there a way to do this without having a custom binding class for each entity class?
Here's the code I have:
In global.asax.cs, Application_Start():
ModelBinders.Binders.Add(typeof(Foo),new FooBinder());
Then in FooBinder.cs:
public override Object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var obj = (Foo)base.BindModel(controllerContext, bindingContext);
var user = controllerContext.HttpContext.User.Identity;
obj.modified_by = user.Name;
obj.modified_date = DateTime.Now;
return obj;
}
Is there a way to generalize this so it can handle multiple types?
We do this in the repository, not in the binder. We have an interface with the common fields (Modified on). We implement the interface in partial classes which we codegen for our entities using a T4 template.
You can use reflection to set fields by name, so that you can do foreach over property names. This is not a big deal since model binder uses reflection itself to get to the properties, anyway. Then you can just register binder for each of the "common" types - which is also OK to do using reflection, for example by checking that entity has all fields required present - so it works even if you add new such entities.
Just have your binder call default one and then update the fields.