Entity framework Code first basics
Entity framework Code first allows you write code without database. first you have create your POCO classis then map with relevant database tables.
To start writing code with EF code first, you need to download relevant "Entity framework Code first" package from Nuget Package manager.
To install EntityFramework, run the following command in the Package Manager Console
PM> Install-Package EntityFramework -Version 4.2.0.0
Create POCO class
using System.ComponentModel.DataAnnotations;
public class BasicUser { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } } public class RegisterUser : BasicUser { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string EmailId { get; set; } } public class User : RegisterUser { public int Id { get; set; } public int RoleId { get; set; } public virtual Role Role { get; set; } } public class PublicUser : User { public string Addess { get; set; } } public class InternalUser : User { public string Dept { get; set; } } public class Role { public int Id { get; set; } [Required] [Display(Name = "Role name")] public string RoleName { get; set; } public string Permissions { get; set; } }
Create DataContext
using System.Data.Entity; using {your model namespace}.Models;
public class DemoDataContext : DbContext { public DemoDataContext() { } public DemoDataContext(string connectionString) : base(connectionString) { } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<News> News { get; set; } public DbSet<UserTask> Tasks { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable("User"); modelBuilder.Entity<Role>().ToTable("Role"); modelBuilder.Entity<News>().ToTable("News"); modelBuilder.Entity<UserTask>().ToTable("Task"); modelBuilder.Entity<PublicUser>() .Map(x=>x.Properties(p=> new { p.Addess })).ToTable("PublicUser"); modelBuilder.Entity<InternalUser>() .Map(x => x.Properties(p => new { p.Dept })).ToTable("InternalUser","dbo"); } public override int SaveChanges() { return base.SaveChanges(); } }
Instatiate DB context
using (var db = new DemoDataContext()) { return db.Users.FirstOrDefault(x => x.Id == id); }
in above example case you need connection sting in your Hosting Application Setting as below;
<connectionStrings> <add name="DemoDataContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=.\Databases\DemoDatabase.sdf" /> </connectionStrings>
Note: name should be same as DataContext Name alternatively you can pass your connection string as below
using (var db = new DemoDataContext("your connection string")) { return db.Users.FirstOrDefault(x => x.Id == id); }
No comments :
Post a Comment