0

我正在使用 ASP.Net MVC4 开发一个项目,我使用 SimpleMembership 来处理会员系统。

除了 UserProfile 表我应该在哪里存储默认数据外,我自己的数据库中有两个表 (Student , Teacher )。

我自定义了注册,添加了一个新字段,我要求新用户定义他是教师还是学生。

public class UsersContext : DbContext
{
    //public UsersContext()
    //    : base("DefaultConnection")
    //{
    //}
    public DbSet<Student> Students { get; set; }
    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<UserProfile> UserProfiles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserProfile>()
            .HasRequired(u => u.Student)
            .WithOptional(p => p.UserProfile)
            .Map(m => m.MapKey("IDStudent"));

        modelBuilder.Entity<UserProfile>()
            .HasRequired(u => u.Teacher)
            .WithOptional(p => p.UserProfile)
            .Map(m => m.MapKey("IDTeacher"));
    }
}

用户资料表变成了这样

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string AccountType { get; set; }
    public virtual Student student { get; set; }
    public virtual Teacher teacher { get; set; }
}

我在 Student , Teacher 两个类中都添加了这个外键

public virtual UserProfile UserProfile { get; set; }

关于帐户控制器/注册类

WebSecurity.CreateUserAndAccount(
    model.UserName,
    model.Password,
    new { AccountType = model.AccountType },
    false);

WebSecurity.Login(model.UserName, model.Password);
UsersContext db = new UsersContext();

var membership = (SimpleMembershipProvider)Membership.Provider;
membership.ValidateUser(model.UserName, model.Password);
membership.ConfirmAccount(model.UserName, model.Password);
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());

if (model.AccountType == "Teacher")
{
    if (userid != null) 
        CreateNewTeacher(user.UserId , model.UserName);
}

if (model.AccountType == "Student")
{
    if (userid != null) 
        CreateNewStudentt(user.UserId , model.UserName);
}

在写完这两个类之后

public void CreateNewStudent( int id, string username)
{
    // Attempt to register the user
    using (UsersContext db = new UsersContext())
    {
        Student student = new Student {User_Name = username};
        student.id=id;
        db.Students.Add(student);
        db.SaveChanges();
    }
}

public void CreateNewTeacher(int id,string username)
{
    using (UsersContext db = new UsersContext())
    {    
        Teacher teacher = new Teacher();
        teacher.id=id;
        db.Teacher.Add(teacher);
        db.SaveChanges();
    }
}

我的问题是:我应该在自己的表中创建用户的级别(我想保持相同的 ID)。所以,我想知道简单的成员资格何时在其表中创建用户以将其复制到我的表中。

我怎样才能得到用户的ID!

难道我对付会计的策略好!还是我这样想错了。

更新 我添加了 [key] (尚未生成)

 public partial class Agent
    {
        public Teacher()
        {
            this.Tasks = new HashSet<Tasks>();
        }

         [Key]
        public int ID_Teacher { get; set; }
        public string Name_Teacher { get; set; }
        public System.DateTime Bday_Teacher { get; set; }
        public string User_Name { get; set; }

        public virtual ICollection<Task> Tasks { get; set; }


    }


  public partial class Task
    {
         [Key, ForeignKey("Teacher"), Column(Order = 0)]
        public int ID_Teacher { get; set; }

         [Key, ForeignKey("Student"), Column(Order = 1)]
        public int ID_Student { get; set; }

         [Key, ForeignKey("DateT"), Column(Order = 2)]
        public int ID_DateT { get; set; }

         [Key]
        public Nullable<int> ID_Comment { get; set; }

        public virtual Teacher Teacher { get; set; }
        public virtual Student Student { get; set; }
        public virtual DateT DateT { get; set; }
    }

感谢您的时间和努力!

问候 ,

4

1 回答 1

0

你需要在one-to-one之间UserProfile and Student,也之间建立关系UserProfile and Teacher。我通常使用Property Mapping而不是fluent api

为实体试试这个,我继续Teacher and Student为你创建了一个关系:

[Table("UserProfile")]
public class UserProfile
{
  [Key]
  [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
  public int UserId { get; set; }
  public string UserName { get; set; }
  public string AccountType { get; set; }   
}


public class Teacher
{
   [Key]
   [ForeignKey("UserProfile")]
   [DatabaseGeneratedAttribute(DatabaseGeneratedOption.none)]
   public int UserId { get; set; }

   public string Name { get; set; }

   public virtual ICollection<Student> Student{ get; set; }
   public virtual UserProfile UserProfile { get; set; }
}

public class Student
{
   [Key]
   [ForeignKey("UserProfile")]
   [DatabaseGeneratedAttribute(DatabaseGeneratedOption.none)]
   public int UserId { get; set; }

   [ForeignKey("Teacher")]       
   public int? TeacherId{ get; set; }

   public string Name { get; set; }

   public virtual UserProfile UserProfile{ get; set; }
   public virtual Teacher teacher { get; set; }
}

在您的帐户控制器中尝试以下操作:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { AccountType = model.AccountType }, false);
                WebSecurity.Login(model.UserName, model.Password);

                var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name)
                                ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);

                if (userProfile.AccountType.ToLower() == "teacher")
                {
                    return RedirectToAction("Create", "Teacher"); //Created a Teacher Controller separate
                }

                return RedirectToAction("Create", "Student"); //same with Student
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

您的StudentTeacher创建操作在学生或教师控制器中应如下所示:

//
    // GET: /Student/
    [HttpGet]
    public ActionResult Create()
    {            
        return View();
    }

    //
    // POST: /Student/
    [HttpPost]
    public ActionResult Create(StudentViewModel model)
    {
        if (ModelState.IsValid)
        {
            using (UsersContext db = new UsersContext())
            {
                var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name)
                                ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);
                if (userProfile != null)
                {
                    var student= new Student
                                     {
                                         UserProfile = userProfile,
                                         Name= model.Name                                                                                          
                                     };                 

                    db.Students.Add(student);                          

                    db.SaveChanges();
                }
            }
        }
        return View(model);
    }
于 2013-04-03T18:47:10.980 回答