我有一个奇怪的情绪,我有一个叫做User的大师班,这是一个抽象类。它包含3个始终从用户继承的儿童班(学生,推广人和BPC)。
我使用TPH(每个层次结构表)结构将其映射到数据库,Discriminator字段只是该类的名称。
学生与推广人有关系。它可以包含0或1个启动子。使用初始化程序,我确保学生具有相应的启动器。 (它在发布后在我的数据库中正确显示)
当我尝试使用modelbinder从登录用户那里获取学生时,它会返回正确的学生,但是它说它不包含推文。
班级用户:
public abstract class User
{
//TPH is default
public int Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Username { get; set; }
public String Email { get; set; }
public String Salt { get; set;}
public String Password { get; set; }
public DateTime LastLogin { get; set; }
public String LastIp { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime CreationDate { get; set; }
[NotMapped]
public String PlainPassword { get; set; }
}
班级学生
public class Student : User
{
public virtual Promotor Promotor { get; set; }
public virtual CoPromotor CoPromotor { get; set; }
public virtual ICollection<Suggestion> Suggestions { get; set; }
public Student()
{
Suggestions = new Collection<Suggestion>();
}
}
班级推广员
public class Promotor : User
{
public virtual ICollection<Student> Students { get; set; }
public List<User> users;
private String message;
public Promotor()
{
Students = new Collection<Student>();
users = new List<User>();
}
}
用户模型活页夹
public class UserModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext.HttpContext.User.Identity.IsAuthenticated)
{
IUserRepository repos =
(IUserRepository) DependencyResolver.Current.GetService(typeof (IUserRepository));
return repos.FindByUsername(controllerContext.HttpContext.User.Identity.Name);
}
return null;
}
}
控制器中的操作
[HttpPost]
public ActionResult Create(CreateViewModel model, User user, string btnSaveSend)
{
var student = (Student) user; //here the attribute Promotor is NULL
}
用户映射器:
public class UserMapper : EntityTypeConfiguration<User>
{
public UserMapper()
{
ToTable("user");
// Primary key
HasKey(u => u.Id);
// Properties
Property(u => u.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(u => u.FirstName).IsRequired();
Property(u => u.LastName).IsRequired();
Property(u => u.Email).IsRequired();
Property(u => u.Salt).IsRequired();
Property(u => u.Username).IsRequired();
Property(u => u.Password).IsRequired();
Property(u => u.LastLogin);
Property(u => u.LastIp);
Property(u => u.CreationDate).IsRequired();
Property(u => u.LastPasswordChangedDate).IsRequired();
}
}
学生映射器
public class StudentMapper : EntityTypeConfiguration<Student>
{
public StudentMapper()
{
HasMany(s => s.Suggestions).WithRequired(s => s.Student);
HasRequired(s => s.Promotor).WithMany(s => s.Students);
}
}
UserRepository:
public User FindByUsername(string name)
{
return users.FirstOrDefault(u => u.Username.ToLower() == name.ToLower());
}