我在从相关域模型返回对象时遇到问题。来自其他模型的对象返回 null。
我基本上想要完成的是返回一个 DTO,其中包含我想要从相关域模型中获得的字段,而不是将每个字段直接从域模型传递给 json。
请参阅下面的代码,有人可以建议。
## CourseDomainModels.cs ##
public class CourseDomainModel : IObjectWithState
{
public int Id { get; set; }
public string Name { get; set; }
public Double Duration { get; set; }
public string Description { get; set; }
public virtual TutorDomainModel CourseTutor { get; set; }
public virtual SubjectDomainModel CourseSubject { get; set; }
public ICollection<EnrollmentDomainModel> Enrollments { get; set; }
[NotMapped]
public Common.State state { get; set; }
[NotMapped]
public bool InDb => this.Id != default(int);
public object PersistenceEntityId => this.Id;
}
## TutorDomainModel.cs ##
public class TutorDomainModel : IObjectWithState
{
public int Id { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Enums.Gender Gender { get; set; }
public ICollection<CourseDomainModel> Courses;
[NotMapped]
public Common.State state { get; set; }
[NotMapped]
public bool InDb => this.Id != default(int);
public object PersistenceEntityId => this.Id;
}
## CourseDTO.cs ##
public class CourseDTO
{
public string Name { get; set; }
public Double Duration { get; set; }
public string Description { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
## AutoMapperConfig.cs ##
public class AutoMapperConfig
{
public static void RegisterMapping()
{
Mapper.CreateMap<CourseDomainModel, CourseDTO>();
}
}
## Startup.cs ##
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
AutoMapperConfig.RegisterMapping();
}
}
## CourseService.cs ##
public CourseDTO GetCourse(int id)
{
var course = _courseRepo.Get(id);
CourseDTO courseView = Mapper.Map<CourseDomainModel,CourseDTO(course);
return courseView;
}