I serialize successfully the following class
[DataContract]
public class Event
{
[DataMember] public virtual string EventId { get; set; }
[DataMember] public virtual string Name { get; set; }
[DataMember] public virtual string Editable { get; set; }
[DataMember] public virtual DateTime? CreatedOn { get; set; }
[DataMember] public virtual Function Function { get; set; }
[DataMember] public virtual User CreatedBy { get; set; }
[DataMember] public virtual IList<EventParameter> Parameters { get; set; }
[DataMember] public virtual IList<EventParameterOption> Options { get; set; }
public Event()
{
Parameters = new List<EventParameter>();
Options = new List<EventParameterOption>();
}
}
but the same code produces an exception when serializing the following
[DataContract]
public class Attribute
{
[DataMember] public virtual string AttributeId { get; set; }
[DataMember] public virtual string Name { get; set; }
[DataMember] public virtual string Description { get; set; }
[DataMember] public virtual string Status { get; set; }
[DataMember] public virtual Function Function { get; set; }
[DataMember] public virtual Category Category { get; set; }
[DataMember] public virtual string Editable { get; set; }
[DataMember] public virtual string Column { get; set; }
[DataMember] public virtual DateTime? LastExecution { get; set; }
[DataMember] public virtual DateTime? LastUpdate { get; set; }
[DataMember] public virtual DateTime? CreatedOn { get; set; }
[DataMember] public virtual User CreatedBy { get; set; }
[DataMember] public virtual IList<AttributeParameter> Parameters { get; set; }
public Attribute()
{
Parameters = new List<AttributeParameter>();
}
}
and the exception points to the User property of the Attribute class.
Type 'UserProxy' with data contract name 'UserProxy:http://schemas.datacontract.org/2004/07/' 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.
The code I use for serializing is
public static byte[] SerializeObjectDataContract(object obj)
{
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(stream, obj);
stream.Position = 0;
return stream.ToArray();
}
}
I really don't understand what differs between the two serializations. Removing the DataMember attribute from the User property allows the serialization to complete, however I do need to serialize the User too.
Related
Here are Entities:
public class Entity
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
}
public class EntityBase : Entity
{
[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public User CreatedBy { get; set; }
[ForeignKey("ModifiedBy")]
public int? ModifiedById { get; set; }
public User ModifiedBy { get; set; }
}
public class ProjectRequest : EntityBase
{
public string RequestTitle { get; set; }
public string RequestType { get; set; }
...
public virtual ICollection<Material> Materials { get; set; }
public virtual ICollection<Translation> Translations { get; set; }
}
public class Material : EntityBase
{
[ForeignKey("ProjectRequest")]
public int ProjectRequestId { get; set; }
public virtual ProjectRequest ProjectRequest { get; set; }
...
public virtual ICollection<Translation> Translations { get; set; }
}
public class Translation:EntityBase
{
[ForeignKey("ProjectRequest")]
public int ProjectRequestId { get; set; }
public virtual ProjectRequest ProjectRequest { get; set; }
[ForeignKey("Material")]
public int MaterialId { get; set; }
public virtual Material Material { get; set; }
public string ProductMasterText { get; set; }
[MaxLength(40)]
public string ShortDescription { get; set; }
public string MasterDescriptionLine1 { get; set; }
public string MasterDescriptionLine2 { get; set; }
public string MasterDescriptionLine3 { get; set; }
public string LanguageCode { get; set; }
}
No modifications has been done to these entities using fluent API.
Now, whenever I try to insert object of type ProjectRequest with Materials and Translations nested in it, in Translation objects ProjectRequestId is set to 0.
Following is sample Change Tracker snapshot:
Can anyone help me on this? Why ProjectRequestId is 0 but MaterialId properly assigned in Transaltion objects?
My EF Code First model for some reason is not in sync with the db. I'm getting this error:
{"Invalid column name 'Type_Id1'."}
The field is actually called 'Type_Id' so I'm not sure from where that 1 comes up. I have the table column called as Type_Id and also I've added a Type_Id in my type entity model.
Why might I be getting that error message, plus why I'm getting 1 at the end of the name?
Update
My Task class:
public class Task
{
public Task()
{
Language = 1;
Grades = new HashSet<Grade>();
Categories = new HashSet<Category>();
Subjects = new HashSet<Subject>();
Rooms = new Collection<Room>();
Tools = new Collection<Tool>();
}
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual TaskType Type { get; set; }
public string Rules { get; set; }
[Required]
[StringLength(200), MinLength(1)]
public string Name { get; set; }
public int PreperationTime { get; set; }
public int InstructionTime { get; set; }
public int TaskTime { get; set; }
public int Type_Id { get; set; }
public string VideoLink { get; set; }
[Required]
public int Language { get; set; }
public int? MinimumParticipants { get; set; }
public int? MaximumParticipants { get; set; }
public int? Rating { get; set; }
[Required]
public string CreatedBy { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
public virtual ICollection<Tool> Tools { get; set; }
}
DBContext class:
public ApplicationDbContext() : base("DefaultConnection", false)
{
}
public DbSet<Task> Tasks { get; set; }
public DbSet<TaskType> TaskTypes { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
You need to add the FK attribute on your navigation property. EF is creating Type_Id1 because Type_Id already exists (although it can't tell by convention it is the FK).
[ForeignKey("Type_Id")]
public virtual TaskType Type { get; set; }
https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships
According to Valueinjecter mapping with source and Target are usually done with naming convention. But it doesn't work in my case , How could i manage mapping of navigation properties.
DTO
public class EmployeeDTO
{
public long EmployeeId { get; set; }
public long? LoginId { get; set; }
public string EmpNumber { get; set; }
public string FirstName { get; set; }
public string CompanyEmail { get; set; }
public string PersonalEmail { get; set; }
public AttendanceTimeSlotDTO AttendanceTimeSlot { get; set; }
}
public class AttendanceTimeSlotDTO
{
public int SlotId { get; set; }
public TimeSpan InTime { get; set; }
public TimeSpan OutTime { get; set; }
}
MYData Provider
public List<EmployeeDTO> GetActiveEmployees()
{
var employees = UnitOfWork.EmployeeRepository.Get(employee => employee.IsActive, null, "AttendanceTimeSlot").ToList();
//This work fine
var employeesDto = employees.Select(x => new EmployeeDTO().InjectFrom(x)).Cast<EmployeeDTO>().ToList();
employeesDto.InjectFrom(employees);
// Not Working
var result =employees.Select(e => new AttendanceTimeSlot().InjectFrom(e)).Cast<AttendanceTimeSlot>()
.Select(x => new EmployeeDTO().InjectFrom(x)).Cast<EmployeeDTO>().ToList();
}
MYEF
public long EmployeeId { get; set; }
public Nullable<long> LoginId { get; set; }
public string EmpNumber { get; set; }
public string FirstName { get; set; }
public virtual ICollection<Attendance> Attendances { get; set; }
public virtual ICollection<PermanentAddress> PermanentAddresses { get; set; }
public virtual ICollection<TemporaryAddress> TemporaryAddresses { get; set; }
public virtual AttendanceTimeSlot AttendanceTimeSlot { get; set; }
How would i map Navigation Properties with OMU.ValueInjector
by default ValueInjecter maps properties with same name and type
the line
employeesDto.InjectFrom(employees);
is not needed, because it doesn't do anything
here:
employees.Select(e => new AttendanceTimeSlot().InjectFrom(e))
I don't see any matching properties between AttendanceTimeSlot and your MYEF
so MYEF doesn't has int SlotId, TimeSpan InTime or TimeSpan OutTime, so the above line return a collection of newly created untouched AttendanceTimeSlot
for an example of using ValueInjecter with EntityFramework (code first) have a look at this demo project: http://prodinner.codeplex.com
I am attempting to use MVC4 for the first time and am receiving the following error when I try to create a controller? Could someone kindly steer me in the right direction?
Microsoft Visual Studio
System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid
in Role 'PropertyData_DNISData_Target' in relationship
'PropertyData_DNISData'. Because the Dependent Role properties are not
the key properties, the upper bound of the multiplicity of the
Dependent Role must be '*'.
public class PropertyData
{
[Key]
public virtual string PropertyID { get; set; }
[ForeignKey ("DNISData")]
public virtual string DNIS { get; set; }
public virtual string PropertyName { get; set; }
public virtual string PropertyGreeting { get; set; }
public virtual string PropertyOperator { get; set; }
public virtual string InvalidEntryPrompt { get; set; }
public virtual string NoEntryPrompt { get; set; }
public virtual string Comment { get; set; }
public virtual DNISData DNISData { get; set; }
}
public class DNISData
{
[Key]
public virtual string DNIS { get; set; }
[ForeignKey("PropertyData")]
public string PropertyID { get; set; }
public virtual string VDN { get; set; }
public virtual string PropertyGreeting { get; set; }
public virtual string Comment { get; set; }
public virtual PropertyData PropertyData { get; set; }
}
public class DigitData
{
[ForeignKey ("DNISData")]
[Key]
public virtual string DNIS { get; set; }
[Key]
public virtual string Digit { get; set; }
public virtual string InvalidEntryPrompt { get; set; }
public virtual DNISData DNISData { get; set; }
}
You have a 1 to 1 relationship between PropertyData and DNISData. This can only be done via shared primarykey in EntityFramework.
This question can give you the anwser you are looking for:
How to declare one to one relationship using Entity Framework 4 Code First (POCO)
Can someone provide an example or explain how can I split a table into more than two entities using data annotations on EF 5 RC Code First?
I have 4 entities I want to be mapped into just one table. The code for each one of them are:
[Table("PatientDataEntities")]
public class PatientDataEntity
{
[Key]
[ForeignKey("UserFullName")]
public virtual Guid Id { get; set; }
public virtual UserFullNameEntity UserFullName { get; set; }
public virtual GeneralData GenData {get; set;}
[ForeignKey("Id")]
public virtual PersonalPatientDataEntity PersonalData { get; set; }
[ForeignKey("Id")]
public virtual MedicalPatientDataEntity MedicalData { get; set; }
[ForeignKey("Id")]
public virtual FinancialPatientDataEntity FinancialData { get; set; }
}
[Table("PatientDataEntities")]
public class PersonalPatientDataEntity
{
[Key]
[ForeignKey("UserFullName")]
public virtual Guid Id { get; set; }
public virtual UserFullNameEntity UserFullName { get; set; }
[ForeignKey("Id")]
public virtual MedicalPatientDataEntity MedicalPatientData { get; set; }
[ForeignKey("Id")]
public virtual FinancialPatientDataEntity FinancialPatientData { get; set; }
[ForeignKey("Id")]
public virtual PatientDataEntity PatientData { get; set; }
[DataType(DataType.DateTime)]
public virtual DateTime Birthdate { get; set; }
public virtual Gender Sex { get; set; }
public virtual MaritalStatus MStatus { get; set; }
public virtual byte Children { get; set; }
public virtual string Education { get; set; }
public string Profession { get; set; }
}
[Table("PatientDataEntities")]
public class MedicalPatientDataEntity
{
[Key]
[ForeignKey("UserFullName")]
public virtual Guid Id { get; set; }
public virtual UserFullNameEntity UserFullName { get; set; }
[ForeignKey("Id")]
public virtual PersonalPatientDataEntity PersonalData { get; set; }
[ForeignKey("Id")]
public virtual FinancialPatientDataEntity FinancialData { get; set; }
[ForeignKey("Id")]
public virtual PatientDataEntity PatientData { get; set; }
public virtual string ClinicalHistoryNumber { get; set; }
public virtual BiologicalState State { get; set; }
public virtual Guid PhysicianId { get; set; }
public virtual DateTime? RegisterDate { get; set; }
public virtual bool AcceptsDataTreatment { get; set; }
public virtual bool AcceptsImageTreatment { get; set; }
public virtual /*List<Allergy>*/ string Allergies { get; set; }
public virtual /*List<Surgery>*/ string Surgeries { get; set; }
public virtual /*List<Medication>*/ string Medications { get; set; }
public virtual /*List<MedicalPrecedent>*/ string MedicalPrecedents { get; set; }
[DataType(DataType.MultilineText)]
public virtual string Family { get; set; }
public virtual string Nicotinism { get; set; }
public virtual float? Weight { get; set; }
public virtual float? Height { get; set; }
[NotMapped]
public virtual float? BodyMassIndex { get; set; }
public virtual string Remarks { get; set; }
}
[Table("PatientDataEntities")]
public class FinancialPatientDataEntity
{
[Key]
[ForeignKey("UserFullName")]
public virtual Guid Id { get; set; }
public virtual UserFullNameEntity UserFullName { get; set; }
[ForeignKey("Id")]
public virtual PersonalPatientDataEntity PersonalData { get; set; }
[ForeignKey("Id")]
public virtual MedicalPatientDataEntity MedicalData { get; set; }
[ForeignKey("Id")]
public virtual PatientDataEntity PatientData { get; set; }
public virtual string KindOfPatient { get; set; }
public virtual string Isapre { get; set; }
}
And my context is this:
public class MedicDbContext : DbContext
{
public DbSet<UserFullNameEntity> UsersFullName { get; set; }
public DbSet<MedicDb.Patient.PatientDataEntity> PatientDataEntities { get; set; }
public DbSet<MedicDb.Patient.Personal.PersonalPatientDataEntity> PersonalPatientDataEntities { get; set; }
public DbSet<MedicDb.Patient.Financial.FinancialPatientDataEntity> FinancialPatientDataEntities { get; set; }
public DbSet<MedicDb.Patient.Medical.MedicalPatientDataEntity> MedicalPatientDataEntities { get; set; }
}
When I run that I receive the following exception:
An exception of type 'System.InvalidOperationException' occurred in
EntityFramework.DLL but was not handled in user code
Additional information: Unable to determine the principal end of an
association between the types
'MedicDb.Patient.Medical.MedicalPatientDataEntity' and
'MedicDb.Patient.Personal.PersonalPatientDataEntity'. The principal
end of this association must be explicitly configured using either the
relationship fluent API or data annotations.
What am I doing wrong here? I really need some help here.
Well, I fixed the problem, I guess the main cause is my ignorance on the topic, the [ForeignKey] attribute must be at just one end of the relation, that fix the exception but to make the 4 entities be on the same table there must be a one to one relation between the 4 of them, it looks a bit unnatural but that's the only way it works. So, at the end I'm not splitting my table but, instead, creating 4 separated tables having one to one relation not among the 4 of them but between the PatientDataEntity and each one of the other 3, that is done by removing the [ForeingKey] annotation from the properties in PatientDataEntity but leaving them on the other 3 entities (on the navigation properties toward PatientDataEntity.
That´s all.
That in case orther people arrives at the same problem.
Thanks to all
Juan Carlos Galvez