Why Appharbor not create all tables.
I have the following Entity Framework Configuration.
public class RezaWebContext : DbContext
{
public RezaWebContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<RegistrantInfo> RegistrantInfos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<RegistrantInfo>().HasRequired(x => x.UserProfile).WithOptional(x => x.RegistrantInfo);
}
}
public class RegistrantInfo
{
public virtual int RegistrantInfoId { get; set; }
public virtual string Name { get; set; }
public virtual string Sex { get; set; }
public virtual string BirthPlace { get; set; }
public virtual string BirthDate { get; set; }
public virtual string Address { get; set; }
public virtual string ExamNumber { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
//this tables used by ASP.Net Simple Membership
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual RegistrantInfo RegistrantInfo { get; set; }
}
connString :
<add name="DefaultConnection" connectionString="server=localhost\SqlExpress; database=RezaWeb;
user id=sa; password=123456; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
in my computer. All database tables created.
RegistrationInfo + SimpleMembership tables (UserProfile, webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_UsersInRoles)
in appharbor : all SimpleMembership tables created but "RegistrationInfo" table not created.
Why ?
Related
I have a grid view and object data source on webpage.Below are the classes created for code first approach.
public class Department
{
public int deptId{ get; set; }
public string deptName { get; set; }
public string location { get; set; }
public List<Employee>Employees { get; set; }
//CodeFirstExample.Employee edf = new Employee();
}
public class Employee
{
public int empId { get; set; }
public string empName { get; set; }
public int salary { get; set; }
public Department Department { get; set; }
}
public class EmployeeDBContext:DbContext
{
public DbSet<Department> Departments{ get; set; }
public DbSet <List<Employee>> Employees { get; set; }
}
public class EmployeeRepository
{
public List<Department> GetDepartments()
{
EmployeeDBContext emp = new EmployeeDBContext();
return emp.Departments.ToList();
}
}
in web.config file connection string as fllowed
<connectionStrings>
<add name="EmployeeDBContext"
connectionString="data source=.\SQLSERVER;initial catalog=Sample; integrated security=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
I created a database using using EF Code-first Migrations approach. When I ran the application I registered a user and expected that the identity tables be added to the database I created but I couldn't find the tables. I checked my connection string to be sure it is rightly set. Please what could I have missed out? Please help.
Edit:
This is the code for the context.
public class AppDataContext : DbContext
{
public AppDataContext()
: base("AppConnection")
{ }
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<Attendance> Attendances { get; set; }
public DbSet<ClassInfo> Classes { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<MessageBoard> MessageBoards { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<Notification_User> UserNotifications { get; set; }
public DbSet<NotificationType> NotificationTypes { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<ParentSubscription> ParentSubscriptions { get; set; }
public DbSet<PrivateMessage> PrivateMessages { get; set; }
public DbSet<School> Schools { get; set; }
public DbSet<SessionPeriod> SessionPeriods { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<TeacherSchool> TeacherSchools { get; set; }
public DbSet<Term> Terms { get; set; }
public DbSet<Work> Works { get; set; }
public DbSet<WorkType> WorkTypes { get; set; }
#region Override Methods
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Subject>()
.HasMany(c => c.Teachers).WithMany(i => i.Subjects)
.Map(t => t.MapLeftKey("SubjectID")
.MapRightKey("TeacherID")
.ToTable("SubjectTeacher"));
modelBuilder.Entity<ClassInfo>()
.HasMany(s => s.Subjects).WithMany(c => c.Classes)
.Map(u => u.MapLeftKey("ClassInfoID").MapRightKey("SubjectID").ToTable("ClassSubject"));
//modelBuilder.Entity<Department>().MapToStoredProcedures();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//modelBuilder.Entity<ClassInfo>()
// .Property(f => f.DateAdded)
// .HasColumnType("datetime2");
}
#endregion
}
When you registered a user :
Refresh your project
Show all files
You will find:
Edit:
IdentityModels.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
//: base("DefaultConnection", throwIfV1Schema: false)
: base("AppConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class AppDataContext : DbContext
{
public AppDataContext()
: base("AppConnection")
{ }
}
Web.config:
<connectionStrings>
<add name="AppConnection" connectionString="Data Source=.; Initial Catalog=SIS_DB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have the following models,do I define it Ok?
User is the main Entity and can have 0..1 to * (zero /one to many relationship ) address.
2.User can have have 0..1 to 1 (one to one userPass )
This is the main table
public class User
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PhoneWork { get; set; }
public string WorkingAt { get; set; }
public virtual UserPass UserPass { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class ConfigModelDbContext : DbContext
{
public DbSet<User> User { get; set; }
public DbSet<Address> Addresses { get; set; }
public DbSet<UserPass> UserPasses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<User>()
.HasOptional(c => c.Addresses).WithRequired(addresses => new User());
modelBuilder.Entity<User>()
.HasOptional(c => c.UserPass).WithRequired(pass => new User());
}
}
Address Class
public class Address
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string UserAddress { get; set; }
}
Userpass class
public class UserPass
{
[Key]
[ForeignKey("User")]
public string UserId { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
i also created classes same as above but can it create relationship directly on database table?
at first I offer you to use data annotation instead of fluent api always.
then correct AddressClass like below:
public class Address
{
[Key]
public int Id { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public string UserId { get; set; }
public string UserAddress { get; set; }
}
This will create Ralationship.
for more details please read Code First DataAnnotations
I am using entity frame work code first approach to design my web application in asp.net 4.5.
I have converted all asp.net membership related tables in code first entities as below
public class Application
{
public string ApplicationName { get; set; }
[Key]
public System.Guid ApplicationId { get; set; }
public string Description { get; set; }
public virtual ICollection<Membership> Memberships { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class Membership
{
[ForeignKey("Application")]
public System.Guid ApplicationId { get; set; }
[Key, ForeignKey("User")]
public System.Guid UserId { get; set; }
public string Password { get; set; }
public int PasswordFormat { get; set; }
public string PasswordSalt { get; set; }
public string Email { get; set; }
public string PasswordQuestion { get; set; }
public string PasswordAnswer { get; set; }
public bool IsApproved { get; set; }
public bool IsLockedOut { get; set; }
public System.DateTime CreateDate { get; set; }
public System.DateTime LastLoginDate { get; set; }
public System.DateTime LastPasswordChangedDate { get; set; }
public System.DateTime LastLockoutDate { get; set; }
public int FailedPasswordAttemptCount { get; set; }
public System.DateTime FailedPasswordAttemptWindowStart { get; set; }
public int FailedPasswordAnswerAttemptCount { get; set; }
public System.DateTime FailedPasswordAnswerAttemptWindowsStart { get; set; }
public string Comment { get; set; }
public virtual Application Application { get; set; }
public virtual User User { get; set; }
}
public class Profile
{
[Key, ForeignKey("User")]
public System.Guid UserId { get; set; }
public string PropertyNames { get; set; }
public string PropertyValueStrings { get; set; }
public byte[] PropertyValueBinary { get; set; }
public System.DateTime LastUpdatedDate { get; set; }
public virtual User User { get; set; }
}
public class Role
{
[ForeignKey("Application")]
public System.Guid ApplicationId { get; set; }
[Key]
public System.Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public virtual Application Application { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User
{
[ForeignKey("Application")]
public System.Guid ApplicationId { get; set; }
[Key]
public System.Guid UserId { get; set; }
public string UserName { get; set; }
public bool IsAnonymous { get; set; }
public System.DateTime LastActivityDate { get; set; }
public virtual Application Application { get; set; }
public virtual Membership Membership { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
My Datacontext and initalizer classes are as below
public class TrainningInitializer : DropCreateDatabaseIfModelChanges<TrainningContext>
{
protected override void Seed(TrainningContext context)
{
}
}
public partial class TrainningContext : DbContext
{
public TrainningContext()
: base("name=TrainningContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
public DbSet<Application> Applications { get; set; }
public DbSet<Membership> Memberships { get; set; }
public DbSet<Profile> Profiles { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
}
I am setting Initializer as below in application_start event inside Global.asax.
Database.SetInitializer<TrainningContext>(new TrainningInitializer());
But when I am running my application I am getting below error
Introducing FOREIGN KEY constraint 'FK_dbo.RoleUsers_dbo.Users_User_UserId' on table 'RoleUsers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
Can someone please help in correcting my entity classes.
When you delete an Application entity this delete cascades to the Roles and the Users and then from Roles to the RoleUsers join table and from the Users to RoleUsers. Those two delete paths from Application to RoleUsers table are the "multiple cascade paths" the exception is talking about. They are not allowed in SQL Server.
Cascading delete is enabled by default for the Roles and Users relationships of Application because the foreign key ApplicationId in these two tables is not nullable, hence the relationship is required. Required relationships have cascading delete turned on by default.
But you can turn it off with Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Application>()
.HasMany(a => a.Roles)
.WithRequired(r => r.Application)
.HasForeignKey(r => r.ApplicationId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Application>()
.HasMany(a => a.Users)
.WithRequired(u => u.Application)
.HasForeignKey(u => u.ApplicationId)
.WillCascadeOnDelete(false);
}
(It's probably sufficient for one of the two.)
If you would delete an Application entity now, you need to delete the related Roles and Users as well. The database won't do that automatically for you anymore.
I have to design a web application using existing database of desktop application. As per existing database i have below class
public class Company
{
#region Primitive Properties
public virtual int CompanyID { get; set; }
public virtual string CompanyName { get; set; }
public virtual bool IsCustomer { get; set; }
public virtual string CustomerCode { get; set; }
public virtual bool IsPotentialCustomer { get; set; }
public virtual bool IsSupplier { get; set; }
public virtual string SupplierCode { get; set; }
public virtual bool IsPotentialSupplier { get; set; }
public CompanyCategoryCodes CustomerCategoryCode { get; set; }
public CompanyCategoryCodes SupplierCategoryCode { get; set; }
public CountryCode CountryCode { get; set; }
}
public class CompanyCategoryCodes
{
public virtual int CategoryID { get; set; }
public virtual string CategoryCodes { get; set; }
public virtual bool PotentialCustomer { get; set; }
public virtual bool PotentialSupplier { get; set; }
public virtual System.DateTime LastModifiedDate { get; set; }
public virtual bool Manufacturer { get; set; }
}
public class CountryCode
{
public virtual int CountryCodeID { get; set; }
public virtual string Code { get; set; }
public virtual string Description { get; set; }
public virtual bool DefaultCode { get; set; }
public virtual bool EECVATApplies { get; set; }
public virtual System.DateTime LastModifiedDate { get; set; }
public virtual bool FixedAddressFormat { get; set; }
}
EF Code first default framework is creating Foreignkey with name "CustomerCategoryCode_CategoryID" , "SupplierCategoryCode_CategoryID", "CountryCode_CountryCodeID". I want this Foreignkey name to be consistance with my old database tables e.g. "CustomerCategoryCodeID", "SupplierCategoryCodeID", "CountryCodeID". How can i do it using EF Code First Fluient API. I try to do it using Fluient API Mapping but i got error for "SupplierCategoryCode_CategoryCodeID" as "CustomerCategoryCode_CategoryID" is also locating to same table "CompanyCategoryCode". Also if is there any option available using Data Annotation then also let me know how to achieve this.
You must manually remap each navigation property to define its key. Something like:
modelBuilder.Entity<Company>()
.HasRequired(c => c.CountryCode)
.WithMany()
.HasForeignKey("CountryCodeID");
modelBuilder.Entity<Company>()
.HasMany(c => c.CustomerCategoryCode)
.WithOptional()
.HasForeignKey("CustomerCategoryCodeID")
.WillCascadeOnDelete(false);
modelBuilder.Entity<Company>()
.HasMany(c => c.SupplierCategoryCode)
.WithOptional()
.HasForeignKey("SupplierCategoryCodeID")
.WillCascadeOnDelete(false);
It is not possible with data annotations unless you define navigation property and foreign key property in each dependent entity like:
public class Company
{
...
[ForeignKey("CountryCode")]
public virtual int CountryCodeID { get; set; }
public CountryCode CountryCode { get; set; }
}
Inside your context class, you will need to override OnModelCreating and map the keys, it should look something like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.HasRequired(c => c.CustomerCategoryCode)
.WithMany()
.Map(mc => mc.MapKey("CustomerCategoryCodeID"));
}