I have an abstract class and another class:
public abstract class AClass
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class BClass: AClass
{
public string OtherName { get; set; }
}
The abstract class have key property, but I received the next error:
Unhandled exception at line 5007, column 9 in /scripts/breeze.debug.js
0x800a138f - JavaScript runtime error: Unable to get property
'propertyRef' of undefined or null reference
Line of error:
breeze.debug.js
var keyNamesOnServer =
toArray(odataEntityType.key.propertyRef).map(__pluck("name"));
The entity "BClass" doesn't contain key property, but abstract class AClass contain key property.
Please, help me with this error.
Edit: As of v 1.3.1 Breeze now DOES support inheritance.
Breeze does not yet support inheritance, but it is on our roadmap. Please vote for this feature on the Breeze User Voice to indicate that you feel that it is important. We take this venue very seriously in prioritizing which features we add next.
Related
I am getting this error "Self referencing loop detected" while serializing using 'Json.NET'
I have a Book model
public class Book
{
public Book()
{
BookPersonMap = new List<BookPersonMap>();
}
public int BookId { get; set; }
public virtual ICollection<BookPersonMap> BookPersonMap { get; private set; }
(And many other virtual Icollections)
}
And this is the BookPerson Mapping class:
public class BookPersonMap
{
public int BookId { get; set; }
public string PersonName { get; set; }
public int PersonTypeId { get; set; }
public virtual Book Book { get; set; } // Foreign keys
public virtual PersonType PersonType { get; set; }
}
When I try to Serialize the Book object it throws:
"Self referencing loop detected for property 'Book' with type 'System.Data.Entity.DynamicProxies.Book_57F0FA206568374DD5A4CFF53C3B41CFDDC52DBBBA18007A896 08A96E7A783F8'. Path 'BookPersonMap[0]'."
I have tried the things suggested in some of the similar posts
Example:
PreserveReferencesHandling = PreserveReferencesHandling.Objects in Serializer settings returned a string with length 3 million!
ReferenceLoopHandling = ReferenceLoopHandling.Ignore in Serializer settings :
"An exception of type 'System.OutOfMemoryException' occurred in Newtonsoft.Json.dll but was not handled in user code"
^ Same luck with "ReferenceLoopHandling.Serialize"
MaxDepth = 1 : Infinite loop again.
Putting [JsonIgnore] on the virtual properties is working but it is a tedious task (because of numerous FK references) and not efficent, since if I miss one property and it will throw exception.
What is missing from above Json settings for them be not working?
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
I have found the best way to solve this type of error is to flatten your model using a view model.
Put a break point on your object before it is serialized and start drilling into the child properties. You will probably find that you can go on indefinitely.
This is what the serializer is choking on.
Create a Constructor for your controller and put on it this line of code :
db.Configuration.ProxyCreationEnabled = false;
//db is the instance of the context.
For asp.net mvc 5 use this
Add the code below to your Application_Start method inside globax.asax file or startup file.
protected void Application_Start()
{
..
GlobalConfiguration.Configuration.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
Disable lazy loading and
ensure your controller does not return
Json(..obj)
rather it should return
Ok(..obj)
I have "many-to-many relationship", which worked perfectly on a local machine until it was time to move to a server. During the move a runtime error was thrown. After upgrade to Entity Framework 6 it worked, but... One of the "many-to-many relationship" was broken.
Models have many properties and they looks something like this:
public partial class CartItem
{
public int id { get; set; }
public virtual ICollection<ProductOptionValue> ProductOptionValues { get; set; }
}
public class CartItemMapping : EntityTypeConfiguration<CartItem>
{
public CartItemMapping() : base()
{
this.HasMany(e => e.ProductOptionValues).WithMany(e => e.CartItems)
.Map(e => e.ToTable("CartItemOptions").MapLeftKey("productOptionValueId").MapRightKey("cartItemId"));
}
}
public class ProductOptionValue
{
public int id { get; set; }
public virtual ICollection<CartItem> CartItems { get; set; }
}
public class ProductOptionValueMapping : EntityTypeConfiguration<ProductOptionValue>
{
public ProductOptionValueMapping() : base()
{
this.HasMany(e => e.CartItems).WithMany(e => e.ProductOptionValues)
.Map(e => e.ToTable("CartItemOptions").MapLeftKey("cartItemId").MapRightKey("productOptionValueId"));
}
}
When getting earlier saved CartItems, ProductOptionValues has count = 0 and there is no way to save a new one.
I found this question on another forum, and only answer was that, this relationship will not work after update at all. But maybe there is a solution?
Or maybe some idea why runtime error was thrown on server with Entity Framework 5?
EDIT
Errors:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_CartItem_CartItemOptions". The conflict occurred in database
"database", table "dbo.CartItems", column 'id'. The statement has been
terminated.
An error occurred while saving entities that do not expose foreign key
properties for their relationships. The EntityEntries property will
return null because a single entity cannot be identified as the source
of the exception. Handling of exceptions while saving can be made
easier by exposing foreign key properties in your entity types. See the InnerException for details.
I am getting this error when attempting to use a Web API controller.
Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type
the code in my controller is as follows
public IEnumerable<Student> GetAllStudents()
{
var allstudents = unitOfWork.StudentRepository.Get(includeProperties: "Groups");
return allstudents;
}
public Student GetStudentByID(Guid id)
{
return unitOfWork.StudentRepository.GetByID(id);
}
and my 'Student' class is as follows
public partial class Student
{
public Student()
{
this.Groups = new HashSet<Group>();
}
public System.Guid StudentID { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public byte[] Timestamp { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
Both methods result in the same error.
My inner exception is as follows
Type
'System.Data.Entity.DynamicProxies.Student_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A'
with data contract name
'Student_4C97D068E1AD0BA62C3C6E441601FFB7418AD2D635F7F1C14B64F4B2BE32DF9A:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
I have a feeling I need to use the KnownType attribute but I'm not exactly sure how to implement it.
Any help would be appreciated
If you don't need the lazy-loaded navigation properties provided by the proxy class (System.Data.Entity.DynamicProxies.Student_4C97D068E1A...), you can disable their generation by setting:
unitOfWork.Configuration.ProxyCreationEnabled = false;
What to do if you need the proxy class is another question.
Follow these links for a good overview of lazy loading and proxies:
Loading Related Entities
Working with Proxies
Should I enable or disable dynamic proxies
I usually disable lazy loading and proxies by default, and enable one or both in specific code blocks that need them.
What is the inner exception message? The inner exception message will be the actual exception that is thrown by the serializer and it should tell us which type is causing the exception.
Let me guess -- Is it any the type Course and the type Group? If so, try putting KnownType attribute on the actual implementation type of your class Student
[KnownType(typeof(GroupA))]
[KnownType(typeof(CourseA))]
public partial class Student
{...}
public class GroupA : Group {...}
public class CourseA : Course {...}
public interface Group {...}
public interface Course {...}
This is my first question, and I've agonised over what to write for a couple of days while Ive been trying to solve this problem.
I bought the Dependency Injection in .NET book by Mark Seeman, and have been trying to follow that and the examples on the Ninject website for creating an abstract factory class. The general idea is that I have a form contains a list of answers to questions. Answers can be of various types, so I am using a factory to create the relevant answer type.
I'm getting the error:
Error activating IAnswerValue
No matching bindings are available, and the type is not self-bindable.
Activation path:
1) Request for IAnswerValue
Suggestions:
1) Ensure that you have defined a binding for IAnswerValue.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
I initially tried with a parameter, but to simplify things for this example, Ive stripped it all out. None of the suggestions given in the error message seem to apply, the factory type is binding, as is the form service but the answervalue is apparently not.
This is the code from my NinjectWebCommon.cs
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.AnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.StringAnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.DateTimeAnswerValue>();
kernel.Bind<IAnswerValueFactory>().ToFactory();
This is the answer class definition:
public class Answer
{
readonly IAnswerValueFactory answerValueFactory;
public int Id { get; set; }
public Question Question { get; set; }
public string Type { get; set; }
public Answer(IAnswerValueFactory answerValueFactory)
{
this.answerValueFactory = answerValueFactory;
}
public void GetAnswerValue()
{
var answer = this.answerValueFactory.GetAnswerValue();
}
public List<AnswerItem> PotentialAnswers { get; set; }
}
and the answer value:
public interface IAnswerValue
{
AnswerValue GetAnswerValue();
}
public class AnswerValue : IAnswerValue
{
readonly IAnswerValue answerValue;
public AnswerValue() { }
public AnswerValue(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public AnswerValue GetAnswerValue()
{
// this will contain a switch statement to
// determine the type returned but I have
// omitted for this example
return new StringAnswerValue();
}
}
public class StringAnswerValue : AnswerValue
{
public string StringAnswer { get; set; }
}
and the factory:
public class AnswerValueFactory : IAnswerValueFactory
{
readonly IAnswerValue answerValue;
public AnswerValueFactory(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public IAnswerValue GetAnswerValue()
{
return (IAnswerValue)this.answerValue.GetAnswerValue();
}
}
I feel like Ive exhausted my knowledge and Im just going around in circles trying the same thing over and over. There must be something quite simple Im missing, but I just cant see what it is.
[DataContract]
public class UserCertification
{
…
}
[DataContract]
public class UserPhone
{
…
}
[DataContract]
public class UserAddress
{
…
}
[DataContract]
public abstract class Request
{
[DataMember]
public int UserMakingRequest { get; set; }
[DataMember]
public Guid RequestId { get; set; }
[DataMember]
public Object RequestObjectDTO { get; set; }
}
var request = new Request
{
RequestId = new Guid(),
UserMakingRequest = loggedInUserId,
RequestObjectDTO = userCertification,
};
I have DataContracts: UserCertification, UserAddress and UserPhone
I also have a DataContact Request. This is what I would like to pass to each WCF service method.
So notice in the Request DataContract is DataMember called RequestObjectDTO. I made this of type object, hoping I would then be able to attach my other DataContracts to it.
This did not work - it throws the error "Cannot create an abstract class."
What type should it be of? Can I do this?
That is the point of abstract class - you can't create its instance. You must create instace of derived non abstract class but in such case you must mark your Request class with KnownTypeAttribute describing child classes which can be transported by WCF messages. Moreover WCF doesn't like object type as DataMember - it will not work because WCF must know what type should be deserialized on a client.
Keep in mind that everything you send to a service must be serialized and deserialized, in most cases, as XML.
Exactly what XML would you have sent to the service, and what XML Schema would describe it? If you can't answer those questions, then neither can WCF.