I have the current entity class Timesheet
:
public class Timesheet
{
#region Properties
public int Id { get; set; }
public DateTime TransactionDate { get; set; }
public int ProjectId { get; set; }
public int AccountId { get; set; }
[MaxLength(50)]
public string Supplier { get; set; }
#endregion
#region Navigation Properties
[ForeignKey("ProjectId")]
public virtual Project CurrentProject { get; set; }
[ForeignKey("AccountId")]
public virtual Account CurrentAccount { get; set; }
#endregion
}
When executing this simple query,
var query = db.Timesheets.AsQueryable();
var data = query;
return data;
I get the following results (note CurrentProject and CurrentAccount ):
<Timesheet>
<AccountId>33</AccountId>
<CurrentAccount i:nil="true"/>
<CurrentProject i:nil="true"/>
<Id>1</Id>
<ProjectId>1064</ProjectId>
<Supplier>Test Supplier</Supplier>
<TransactionDate>2016-02-27T00:00:00</TransactionDate>
</Timesheet>
However, when trying to explicitly load related objects,
var query = db.Timesheets.AsQueryable();
var data = query.Include(n => n.CurrentProject);
return data;
I get a serialization error:
The 'ObjectContent 1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'
<ExceptionMessage>
Type 'System.Data.Entity.DynamicProxies.Timesheet_B61B0CCFFB38C448231EBA3EF4D3D57C851AD2AE97FAA0BF8AA7F175D4C507D6' with data contract name 'Timesheet_B61B0CCFFB38C448231EBA3EF4D3D57C851AD2AE97FAA0BF8AA7F175D4C507D6: 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.</ExceptionMessage>
I ran a similar query using LINQPad
and got correct results with all the related objects so I don't know what's wrong here.
I'm a n00b here and can really use your help!
It's almost certainly due to a navigation property from Project back to the Timesheet.
When Timesheet is being serialized, so is the CurrentProject property. That, in turn, references the Timesheet, resulting in a circular reference.
Decorate the Timesheet navigation property on Project class to prevent it being serialized: [JsonIgnore]
. You'll have to do the same with the Account class if you .Include() that, too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.