I need your help in guiding may into good way of implement the Model in MVC4.
I will let you see my model. But I really don’t know how to link that to Membership Provider in MVC4
I want to build tender application system and I have the following models
Tender: who add projects?
Supplier/provider : who bid for projects
Projects: Projects added by tenders ( Done)
Requirements: each projects had several requirements.(Done)
I did the project And requirement Model.. But am not sure how to do the tender and suppliers!! Because both of them have to register ..!?
2.Is my relation many to many is correct? Between Project and Requirement table.?
Now those are my model with context:
public class ProjectContext : DbContext
{
public ProjectContext()
: base("ProjectsDB")
{
}
public DbSet<ProjectEntry> Entries { get; set; }
public DbSet<Requiernments> RequiernmentEntries { get; set; }
//public DbSet<UserProfile> UserProfiles { get; set; }
}
public class ProjectEntry
{
[Key]
public int ID { get; set; }
[Required]
public string ProjectName { get; set; }
public string Description { get; set; }
public string Statue {get; set; }
public string UplodedFiles { get; set; }
public string Budget { get; set; }
public string EstimateTime { get; set; }
public string Criterias { get; set; }
public DateTime? DueDate { get; set; }
}
public class Requiernments
{
[Key]
public int RequiernmentId { get; set; }
public int ID { get; set; }
public string RequiernmentName { get; set; }
/// <summary>
/// 1: Must to Have
/// 2: Nice to Have
/// 3: Should have
/// </summary>
public string RequiernmentType { get; set; }
public string RequiernmentPrioritet { get; set; }
public float RequiernmenWhight { get; set; }
public string ProviderAnswer { get; set; }
public string ProviderComments{ get; set; }
}:
update 2:
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
if (!Roles.RoleExists("Admin"))
Roles.CreateRole("Admin");
if (!Roles.RoleExists("Member"))
Roles.CreateRole("Member");
if (!Roles.RoleExists("Tender"))
Roles.CreateRole("Tender");
if (!Roles.RoleExists("Provider"))
Roles.CreateRole("Provider");
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
new
{
EmailAddress = model.EmailAddress
}, false);
Roles.AddUserToRole(model.UserName, "Member");
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
AND
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=user-Pc\SQL2012;Initial Catalog=MemberDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MemberDB.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
image:
http://i58.tinypic.com/2rp8i86.png
If I understand correctly, in your application you have two roles, tender and supplier. In addition, you want to tender to be able to add project and then associate requirements with project.
In order to achieve that, first of all you need to config SimpleMembershipProvider to have two roles "tender" and "supplier"
First in the configuration file, replace the classic membership provider with SimpleMembershipProvider by doing this
enable migrations
seed membership and roles
protected override void Seed(MovieDb context)
{
//context.Movies.AddOrUpdate(...);
// ...
SeedMembership();
}
private void SeedMembership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
var roles = (SimpleRoleProvider) Roles.Provider;
var membership = (SimpleMembershipProvider) Membership.Provider;
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (membership.GetUser("sallen",false) == null)
{
membership.CreateUserAndAccount("sallen", "imalittleteapot");
}
if (!roles.GetRolesForUser("sallen").Contains("Admin"))
{
roles.AddUsersToRoles(new[] {"sallen"}, new[] {"admin"});
}
}
step 1,2,3 reference:
Scott Allen's blog
Now create your model
public class Tender
{
public int TenderId { get;set;}
public int UserId {get;set;} //this links to the userid in the UserProfiles table
public virtual ICollection<Project> Projects {get;set;}
}
public class Project
{
public int ProjectId {get;set;}
public int TenderId {get;set;}
public virtual Tender Tender {get;set;}
public virtual ICollection<Supplier> Suppliers {get;set;}
public virtual ICollection<Requirement> Requirements {get;set;}
}
public class Supplier
{
public int SupplierId {get;set;}
public virtual ICollection<Project> Projects {get;set;}
}
public class Requirement
{
public int RequirmentId {get;set;}
public int ProjectId {get;set;}
public virtual Project Project {get;set;}
}
because supplier can bid multiple projects and projects can have multiple bidders, therefore supplier and project have a multiple to multiple relationship, you probably want to have a mapping table.
In the OnModelCreating Method,
modelBuilder.Entity<Project>()
.HasMany(p => p.Suppliers)
.WithMany(s => s.Projects)
.Map(map =>
{
map.ToTable("Project_Supplier_Map")
.MapLeftKey("SupplierId")
.MapRightKey("ProjectId");
});
Now you have your model and just need to decorate your class with Authorize attribute
Related
In ASP.NET Core-6 Web API application, I am using Entity Framework for Self-Referencing. I have this model:
public class Merchant
{
public Guid Id { get; set; }
public string MerchantName { get; set; }
public Guid? ParentId { get; set; }
public string NotificationUrl { get; set; }
public virtual Merchant ParentMerchant { get; private set; }
public virtual ICollection<Merchant> SubMerchants { get; private set; }
}
AAs shown above, ParentMerchant (ParentId) will have many SubMerchants. ParentId is optional and nullable.
So far, I have written the Fluent API as shown below:
public class MerchantConfigurations : IEntityTypeConfiguration<Merchant>
{
public void Configure(EntityTypeBuilder<Merchant> builder)
{
builder.ToTable(name: "merchants");
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).HasDefaultValueSql("NEWID()");
builder.HasIndex(m => m.MerchantName).IsUnique();
}
}
How do I include the Self-Referencing Rule for ParentId, ParentMerchant and SubMerchants in the Config above using FluentAPI?
Thank you
I'm new to Entity Framework and I'm trying to create database for my Android application using Entity Framework with a code-first approach (I think).
My database would look like this:
In the Restaurant table, I would like to have a list of Dish table elements and same for Groceries in the Dish table.
I tried to do it like this:
https://entityframework.net/knowledge-base/41048304/entity-framework-class-with-list-of-object
But I can't see the FK in migration or in the database.
Next I tried it like this code below (here are my classes) :
public class Restaurant
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdRestaurant { get; set; }
[Required]
public String NameOfRestaurant { get; set; }
[Required]
public String Location { get; set; }
[Required]
public String PictureOfRestaurant { get; set; }
public virtual ICollection<Dish> Dishes { get; set; }
[Required]
public String UserId { get; set; }
public ApplicationUser User { get; set; }
}
public class Dish
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdDish { get; set; }
[Required]
public String NameOfDish { get; set; }
[Required]
public String PictureOfDish { get; set; }
[Required]
public Double Price { get; set; }
[Required]
public Double CalorieValue { get; set; }
public virtual int? IdRestaurant { get; set; }
public virtual Restaurant Restaurant { get; set; }
public virtual ICollection<Grocery> Groceries{ get; set; }
[Required]
public String UserId { get; set; }
public ApplicationUser User { get; set; }
}
public class Grocery
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdGrocery { get; set; }
[Required]
public String NameOfGrocery { get; set; }
[Required]
public String PictureOfGrocery { get; set; }
[Required]
public Double CalorieValue { get; set; }
public virtual int? IdDish { get; set; }
public virtual Dish Dish { get; set; }
[Required]
public String UserId { get; set; }
public ApplicationUser User { get; set; }
}
But it didn't work.
After I solve this problem, I would like to add some elements in database. Tried it like this (just to test if it works, but with no success) :
internal sealed class Configuration : DbMigrationsConfiguration<Restaurants.Models.MojDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Restaurants.Models.MojDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Groceries.AddOrUpdate(x => x.IdGrocery,
new Grocery()
{
NameOfGrocery = "Carrot",
PictureOfGrocery = "anhnahdagd",
CalorieValue = 55
},
new Grocery()
{
NameOfGrocery = "Tomato",
PictureOfGrocery = "wqeqwewqeewqqew",
CalorieValue = 89
},
new Grocery()
{
NameOfGrocery = "Potato",
PictureOfGrocery = "zuuuiitutuitu",
CalorieValue = 110
}
);
context.SaveChanges();
}
}
And when I add a migration with:
Add-Migration SeedMigration
it just creates a blank migration :
public partial class SeedMigration : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
So how can I add data into the table?
Create foreign key
To create a foreign key, you have to add a line that is an [Index], with a name (in this example) U_FK and then add [Required] at the end.
[Index]
public int U_FK { get; set; } // Foreign Key - User
[Required]
Create list of foreign key
To create a foreign key, you have to add a line that is an [Index], with a name (in this example) U_FK and then add [Required] at the end.
[Index]
public List<int> U_FK { get; set; } // Foreign Key - User List
[Required]
Add elements to database
To add elements you first call the class name and create a new instance of it, in this case exp. Then you assign it's values (as long as they aren't required you don't have to). After that you load your context and save it in ExampleList you created (will show example below).
Example exp = new Example
{
Active = true,
Titel = InputTitel,
Views = 0,
};
using(var context = new ForumDbContext())
{
context.Examples.Add(exp);
context.SaveChanges();
}
Create a Context (if you don't already have one)
In your specific case you can replace Context with your already existing seed migration.
public class GlobalRef
{
public static string dbConnectionString = "Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = FForumDB; Integrated Security = True; MultipleActiveResultSets=True";
}
public class ForumDbContext : DbContext
{
public ForumDbContext() : base(GlobalRef.dbConnectionString) {}
public DbSet<Example> Examples{ get; set; }
}
Get Value from database
To get for example the ID of another Datatable. You first get the context again. Then you loop through each element in that Database where it's active and order it by views. You can also add .First() to only get the first element that was returned.
using(ForumDbContext context = new ForumDbContext())
{
foreach(Example example in context.Examples.SqlQuery("SELECT * FROM Examples WHERE Active='1' ORDER BY Views" ).ToList<Example>())
{
int exampleid = example.E_ID;
}
}
Get all Values from database and put them in a List
List<int> exampleFKs = new List<int>;
using(ForumDbContext context = new ForumDbContext())
{
foreach(Example example in context.Examples.SqlQuery("SELECT * FROM Examples WHERE Active='1' ORDER BY Views" ).ToList<Example>())
{
exampleFKs.Add(example.E_ID);
}
}
I am trying to follow tutorials online to help me get roles setup in my MVC project, but seem to be failing to understand everything. My company required that I create my project Database First, rather than code first, so my roles already exist in my dbContext. I do not want to create a controller to Index, Create, Edit, etc. my Roles, at least not at this step, but I DO want to know what userGroup my users belong to, to then refer to their userGroup as their role.
So, I have two Models; one for users and one for userGroups (essentially a "roles" table):
public partial class User : IdentityUser
{
public int UKey { get; set; }
public int UgKey { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string EmailAddress { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool UseBrightreeAuth { get; set; }
public bool Active { get; set; }
}
public partial class UserGroup
{
public int UgKey { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
I have a Account Controller that handles the "logging in" of my website:
public ActionResult Login(LoginViewModel login)
{
if (!ModelState.IsValid)
{
ViewBag.Error = "Form is not valid; please review and try again.";
return View("Login");
}
using (var wfc = new WorkflowContext())
{
if(wfc.User.Where(x => x.Username == login.Username).Any())
{
//ignore the bad logic/LINQ, it's temporary...
var UserManager = new UserManager<User>(new UserStore<User>(wfc));
UserManager.AddToRole("UserName", "UserRole");
}
else
{
ViewBag.Error = "Credentials invalid. Please try again.";
return View("Login");
}
}
}
the following line of code will not compile, saying wfc is not a valid argument, but I am not sure what I should be using instead?
//Where wfc is the Context that contains my User and UserGroup Tables
var UserManager = new UserManager<User>(new UserStore<User>(wfc));
I get the error
Cannot convert from "Workflow.Models.WorkflowContext" to "System.Data.Entity.DbContext"
Is there a better way to add a user to a role or am I misunderstanding the process? Thanks.
I am Using EF 6.0 and want to combine AppDbContext & IdentityDbContext into a single context which is AppDbContext.
This is a requirement as i have other tables which has relations with the AspNetUsers table created by EF.
The problem is EF is creating two tables for Users such as AspNetUsers and IdentityUsers.
Also If i use DbSet<ApplicationUser> in DbContext instead of DbSet<IdentityUsers> , Then add-migration throws up error.
My AppDbContext is
public class AppDbContext : IdentityDbContext<ApplicationUser>,IDisposable
{
public AppDbContext()
: base("MvcArchBSEFDB", throwIfV1Schema: false)
{
}
public static AppDbContext Create()
{
return new AppDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
//public DbSet<ApplicationUser> AppUsers { get; set; } // breaks migration
//Multiple object sets per type are not supported. The object sets 'AppUsers ' and 'Users' can both contain instances of type 'MvcArchBS.DAL.Setp.ApplicationUser'.
public DbSet<IdentityUser> AppUsers { get; set; } // Creates Two Tables AspNetUsers & IdentityUser
public DbSet<IdentityUserRole> UserRoles { get; set; }
public DbSet<IdentityUserClaim> Claims { get; set; }
public DbSet<IdentityUserLogin> Logins { get; set; }
public DbSet<Module> Modules { get; set; }
public DbSet<SubModule> SubModules { get; set; }
public DbSet<PageMst> Pages { get; set; }
public void Dispose()
{
base.Dispose();
}
}
And My ApplicationUser Class is
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
status = "A";
reptngusrid = "admin";
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int usrid { get; set; }
public string usrdescr { get; set; }
public int empid { get; set; }
public int usrgrpid { get; set; }
[StringLength(1)]
public string status { get; set; }
public string reptngusrid { get; set; }
public int defmodid { get; set; }
[StringLength(20)]
public string cltur { get; set; }
[ForeignKey("defmodid")]
public virtual Module Module { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
How do i get this to work ? I want to use something like context.AppUsers in my queries which i am unable to get.
It turns out my Service Layer Project also needs a reference to Microsoft.AspNet.Identity.EntityFramework.dll.
Once i added that all identity entity sets are available now with my context.
Also as tmg & Brendan had pointed out the IdentityDbContext members DbSets are not required in the AppDbContext.
Hope this helps someone.
I'm writing an MVC5 application with EF6 which allows users to enter job timesheets, job notes and email the customer an update.
I want my database structure to compose of 3 tables for this (Timers, JobNotes and Emails). I can have 3 models like this;
[Table("Timers")]
public partial class TimerModel
{
public int ID { get; set; }
public string User { get; set; }
...etc
public virtual CustomerEmailModel CustomerEmail { get; set; }
}
[Table("JobNotes")]
public partial class JobNoteModel
{
public int ID { get; set; }
[Column("Username")]
public string User { get; set; }
...etc
public virtual CustomerEmailModel CustomerEmail { get; set; }
}
[ComplexType]
public partial class CustomerEmailModel
{
[Display(Name = "Email Customer?")]
public bool SendEmail { get; set; }
[DataType(DataType.EmailAddress)]
public string To { get; set; }
public string Subject { get; set; }
[DataType(DataType.MultilineText)]
public string Body { get; set; }
}
But this obviously doens't create the Email table, and instead adds the properties to the Timer and JobNotes tables (e.g. Email_SendEmail, Email_To, etc).
If i remove the [ComplexType] annotation, and change my other models to have;
public int? EmailID { get; set; }
[ForeignKey("EmailID")]
public virtual CustomerEmailModel CustomerEmail { get; set; }
Then it does create the table, but then i'm unsure of how to add new entries (i.e. emails are added on the fly, with a 0..1 relationship. It would mean that i would need to add to the email explicitly, get the added entries ID, and then assign it to the other model (timer or jobnote model) EmailID.
Is there a better way of doing this?
Thanks for any help in advance. Please let me know if you need any further information.
EDIT:
It seems that I do need to provide more information from the answers I'm getting so far.
I have two databases in play. A vendor supplied database, for an application which records job, timesheet, employee, customer, etc information. Lets call it DB01.
And a database (call it DB02) for my application (its a mobile app for users to record timesheet or jobnote information, and submit it to DB01).
The mobile app has a user interface which has the following key inputs;
Start Time, Stop Time, Break Time, Job Selector (drop down), Timesheet Title, Timesheet Notes, Send Email To Customer (checkbox), To Address, Subject, Body.
As such, a complex type does work correctly (and is what i'm using in the interm). However, because I have another page which will be able to email the customer as well, I wanted a separate email table (however, i don't want to have to save the email separately, and then assign it to the timesheet or jobnote).
Also - the only tables i need (for DB02), are the ones to store the timesheet, jobnote and email data. Once the timesheet or jobnote gets submitted, it can be deleted or archived. I only need these tables, because all other relevant information is contained in DB01. I can retrieve this data from views on DB02, and i can submit the information from DB02 to DB01 with a stored procedure from DB02. (DB02 has DB01 as a linked server)
This is a simple example of the use of foreign keys with EF6
public class A
{
public int Id { get; set; }
public virtual B Bobject { get; set; }
public int BId;
public virtual ICollection<C> Cs { get; set; }
}
public class B
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<A> As { get; set; }
}
}
public class C
{
public int Id { get; set; }
public string TransactionId { get; set; }
public virtual A Aobj { get; set; }
public int AId { get; set; }
}
You have quite big issues with your database to begin with, and you're not clearly defining the different sets of data.
I've redeveloped what you're trying to achieve using the Fluent API.
public class TimeSheet
{
public TimeSheet()
{
this.TimeSheetId = Guid.NewGuid()
.ToString();
}
public virtual Employee Employee { get; set; }
public string EmployeeId { get; set; }
public virtual Job Job { get; set; }
public string JobId { get; set; }
public string TimeSheetId { get; set; }
}
public class Employee
{
public Employee()
{
this.EmployeeId = Guid.NewGuid()
.ToString();
}
public string EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public virtual ICollection<TimeSheet> TimeSheets { get; set; }
public virtual ICollection<Mail> MailsSent { get; set; }
}
public class Job
{
public Job()
{
this.JobId = Guid.NewGuid()
.ToString();
}
// One job will have one client
public virtual Client Client { get; set; }
public string ClientId { get; set; }
public string JobId { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
// A Job may have many time sheets
public virtual ICollection<TimeSheet> TimeSheets { get; set; }
}
public class Client
{
public Client()
{
this.ClientId = Guid.NewGuid()
.ToString();
}
public string ClientId { get; set; }
public string EmailAddress { get; set; }
// A client can have many work packages / jobs.
public virtual ICollection<Job> WorkPackages { get; set; }
public virtual ICollection<Mail> Mails { get; set; }
}
public class Mail
{
public Mail()
{
this.MailId = Guid.NewGuid()
.ToString();
}
// A mail item will reference one client.
public virtual Client Client { get; set; }
public string ClientId { get; set; }
public string MailId { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public string EmployeeId { get; set; }
// A mail item will also originate from an employee
public virtual Employee Employee { get; set; }
// This doesn't belong here... as if it isn't
// being sent, then it wouldn't make sense to create
// create the email in the first place...
// If you want to queue emails, rename the field to `IsSent`
//
// public bool SendEmail { get; set; }
}
public class TimeSheetConfiguration : EntityTypeConfiguration<TimeSheet>
{
public TimeSheetConfiguration()
{
this.ToTable("TimeSheets");
this.HasKey(timeSheet => timeSheet.TimeSheetId);
this.Property(property => property.TimeSheetId).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(property => property.JobId) .IsRequired();
this.Property(property => property.EmployeeId) .IsRequired();
this.HasRequired(timeSheet => timeSheet.Job) .WithMany(job => job.TimeSheets).HasForeignKey(timeSheet => timeSheet.JobId);
this.HasRequired(timeSheet => timeSheet.Employee).WithMany(emp => emp.TimeSheets).HasForeignKey(timeSheet => timeSheet.EmployeeId);
}
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
this.ToTable("Employees");
this.HasKey(emp => emp.EmployeeId);
this.Property(property => property.EmployeeId) .IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(property => property.FirstName) .IsRequired();
this.Property(property => property.LastName) .IsOptional();
this.Property(property => property.EmailAddress).IsRequired();
this.HasMany(employee => employee.TimeSheets).WithRequired(time => time.Employee).HasForeignKey(time => time.EmployeeId);
this.HasMany(employee => employee.MailsSent) .WithRequired(mail => mail.Employee).HasForeignKey(mail => mail.EmployeeId);
}
}
public class ClientConfiguration : EntityTypeConfiguration<Client>
{
public ClientConfiguration()
{
this.ToTable("Clients");
this.HasKey(client => client.ClientId);
this.Property(property => property.ClientId) .IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(property => property.EmailAddress).IsRequired();
this.HasMany(property => property.WorkPackages).WithRequired(job => job.Client) .HasForeignKey(job => job.ClientId);
this.HasMany(property => property.Mails) .WithRequired(mail => mail.Client).HasForeignKey(mail => mail.ClientId);
}
}
public class JobConfiguration : EntityTypeConfiguration<Job>
{
public JobConfiguration()
{
this.ToTable("Jobs");
this.HasKey(job => job.JobId);
this.Property(property => property.JobId) .IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(property => property.Name) .IsRequired();
this.Property(property => property.ClientId).IsRequired();
this.Property(property => property.Notes) .IsRequired();
this.HasMany(job => job.TimeSheets).WithRequired(time => time.Job) .HasForeignKey(time => time.JobId);
this.HasRequired(job => job.Client).WithMany (client => client.WorkPackages).HasForeignKey(job => job.ClientId);
}
}
public class MailConfiguration : EntityTypeConfiguration<Mail>
{
public MailConfiguration()
{
this.ToTable("Mails");
this.HasKey(mail => mail.MailId);
this.Property(property => property.MailId) .IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(property => property.ClientId) .IsRequired();
this.Property(property => property.EmployeeId).IsRequired();
this.Property(property => property.Subject) .IsRequired();
this.Property(property => property.Body) .IsRequired();
this.HasRequired(mail => mail.Client) .WithMany(client => client.Mails) .HasForeignKey(mail => mail.ClientId);
this.HasRequired(mail => mail.Employee).WithMany(employee => employee.MailsSent).HasForeignKey(mail => mail.EmployeeId);
}
}
public class ExampleContext : DbContext
{
public DbSet<Mail> Mails { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<TimeSheet> TimeSheets { get; set; }
/// <summary>
/// This method is called when the model for a derived context has been initialized, but
/// before the model has been locked down and used to initialize the context. The default
/// implementation of this method does nothing, but it can be overridden in a derived class
/// such that the model can be further configured before it is locked down.
/// </summary>
/// <remarks>
/// Typically, this method is called only once when the first instance of a derived context
/// is created. The model for that context is then cached and is for all further instances of
/// the context in the app domain. This caching can be disabled by setting the ModelCaching
/// property on the given ModelBuidler, but note that this can seriously degrade performance.
/// More control over caching is provided through use of the DbModelBuilder and DbContextFactory
/// classes directly.
/// </remarks>
/// <param name="modelBuilder">The builder that defines the model for the context being created. </param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MailConfiguration());
modelBuilder.Configurations.Add(new ClientConfiguration());
modelBuilder.Configurations.Add(new EmployeeConfiguration());
modelBuilder.Configurations.Add(new TimeSheetConfiguration());
modelBuilder.Configurations.Add(new JobConfiguration());
base.OnModelCreating(modelBuilder);
}
}