0

我正在使用ASP.Net MVC4使用SimpleMembership處理成員資格系統的項目。在MVC 4/EF中自定義SimpleMembership與我自己的數據庫4/EF

除了UserProfile表,我應該在哪裏存儲默認數據,我有兩個表在我自己的數據庫(學生,老師)。

我定製了註冊,添加了一個新字段,我要求新用戶定義他是老師還是學生。

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; } 
} 

我加入這兩個班的學生外鍵,教師

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!

我的會計策略處理好嗎!或者我錯誤地思考這種方式。

UPDATE 我已經添加[關鍵](它尚未產生)

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; } 
    } 

我很欣賞你的時間和精力!

問候,

+0

好像你已經找到了用戶的ID。這似乎更像是[代碼評論](http://codereview.stackexchange.com/)的問題 – Artless

+0

我感謝您的幫助,每當我保存時我都會遇到問題(教師/客戶端)「EntityType'Teacher'沒有定義密鑰。「知道我從SQL Server數據庫生成我自己的數據庫任何建議! – ImnotaGeek

+0

你可以發佈你的'教師'類嗎? – Artless

回答

0

您需要創建UserProfile and Student之間的關係one-to-one,也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); 
    } 
+0

謝謝!我已經試過了,它'老師'的id沒有被自動遞增(所有的時間都是val 0,我將採用這個策略,這很簡單:: http://stackoverflow.com/questions/15333324/如何填充自定義屬性表使用simplemembership-in-asp-net)我得到了這個異常「無法確定類型'任務'的組合主鍵排序。使用ColumnAttribute或HasKey方法來指定組合主鍵的順序。「 – ImnotaGeek

+0

我仍在寫它,給我一秒,我會寫你一個行動 – Komengem

+0

謝謝,我正在嘗試它;如果我我們沒有錯,我們需要添加「public int TeacherId {get;組; }「to」Teacher「Entity! – ImnotaGeek

相關問題