نحوه افزودن یک فیلد به UserProfile در SimpleMemberShip
۷ اسفند ۱۳۹۱
بدون دیدگاه
این مطالب بر مبنای MVC4 و .Net Framewrok 4 و Code First می باشد
اگر بخواهیم فیلدی برای UserProfile اضافه کنیم بترتیب زیر عمل می کنیم
۱- فایل Models\Account.cs را باز می کنیم و دو تا فیلد موبایل و ایمیل را اضافه می کنیم
1 2 3 4 5 6 7 8 9 10 |
[Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string Mobile { get; set; } public string Email { get; set; } } |
2- کلاس UserProfile را در بخشی کهDBContext تعریف شده اضافه می کنیم مثلا
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class myDBContext : DbContext { public senfDBContext() : base("name=myDBContext") { } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<Education> Educations { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } |
3- شاید لازم باشد پراپرتی مقدار دهی اولیه simplemembership از فایل AccountControl.cs حذف شود
1 2 3 4 5 6 |
namespace myproject.Controllers { [Authorize] //[InitializeSimpleMembership] public class AccountController : Controller { |
4- حالا می شود از متد seed برای مقدار دهی اولیه مدل UserProfile استفاده کرد. ساده ترین راه استفاده از migrations\configuration.cs می باشد
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
internal sealed class Configuration : DbMigrationsConfiguration<myproject.Models.senfDBContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(myproject.Models.senfDBContext context) { SeedMembership(); private void SeedMembership() { WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); //var roles = (SimpleRoleProvider)Roles.Providers; //var membership = (SimpleMembershipProvider)Membership.Providers; if (!Roles.RoleExists("Administrator")) Roles.CreateRole("Administrator"); if (!WebSecurity.UserExists("admin")) WebSecurity.CreateUserAndAccount( "admin", "123456", new { Mobile = "+9121230000", Email = "f@f.com"}); // if (!Roles.GetRolesForUser("admin").Contains("Administrator")) // Roles.AddUsersToRole(new[] { "admin" }, new[] { "Administrator" }); if (!Roles.GetRolesForUser("admin").Contains("Administrator")) Roles.AddUsersToRole(new string[] {"admin"}, "Administrator"); } } } |
5- سپس پروژه را بیلد می کنیم
۴- اجرای دستور زیر در Package Manager از منوی Tools\Library Package Manager
1 |
PM>update-database -verbose |
6- اگر خطایی رخ دهد بهترین راه حل حذف دیتابیس می باشد و سپس اجرای دستور update-database
Categories: Code First, MVC