简体   繁体   中英

Entity Framework: Help Creating Database using Code first Approach

OK 2 questions: 1. I am new to Databases and I want to learn the code first approach to creating a Database. I have used the Model-first approach a few times. Can anyone help me with coding this DB using Code-first approach (I also would like to add an Employee table if possible)? Here is the link to the DB Diagram:

http://databaseanswers.org/data_models/customers_and_orders/images/customers_and_orders_ref_data_model.gif

  1. Also, how would I insert into lets say the customer table / customer address address all in one go, using entity framework of course?

Thank you in advance for anyone willing to help.

You can do it like follows:

Please note the this solution has done as a console application.

Please add the following class to do this as code first:

        public class Customer
            {
                [Key]
                public int CustomerId { get; set; }
                public string FirstName { get; set; }
                public string MiddleName { get; set; }
                public string LastName { get; set; }
                public string Phone { get; set; }
                public string Email { get; set; }
                public string CustomerOtherDetails { get; set; }
            }

            public class CustomerAddress
            {
                [ForeignKey("Customer")]
                public int CustomerId { get; set; }
                [ForeignKey("AddressType")]
                public int AddressTypeId { get; set; }
                [ForeignKey("Address")]
                public int AddressId { get; set; }
                [Key]
                public DateTime DateFrom { get; set; }
                public DateTime DateTo { get; set; }
                public virtual Customer Customer { get; set; }
                public virtual AddressType AddressType { get; set; }
                public virtual Address Address { get; set; }
            }

            public class AddressType
            {
                [Key]
                public int AddressTypeId { get; set; }
                public string AddressTypeDescriptiom { get; set; }
            }

            public class Address
            {
                [Key]
                public int AddressId { get; set; }
                public string Line1 { get; set; }
                public string Line2 { get; set; }
                public string Line3 { get; set; }
                public string City { get; set; }

            }

When you do it Code First approach you need to create the model out of the class you created and it can be done as follows:

Context class should be like follows:

    public class CustomerContext : DbContext
    {
        public CustomerContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CustomerContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Customer table
            modelBuilder.Entity<Customer>().HasKey(m => m.CustomerId);


            //set primary key to Address table
            modelBuilder.Entity<CustomerAddress>().HasKey(m => m.DateFrom);

            modelBuilder.Entity<AddressType>().HasKey(m => m.AddressTypeId);
            modelBuilder.Entity<Address>().HasKey(m => m.AddressId);

            //Set foreign key property
            modelBuilder.Entity<CustomerAddress>().HasRequired(t => t.Customer)
                .WithMany().HasForeignKey(t => t.CustomerId);

            modelBuilder.Entity<CustomerAddress>().HasRequired(t => t.AddressType)
                .WithMany().HasForeignKey(t => t.AddressTypeId);

            modelBuilder.Entity<CustomerAddress>()
                .HasRequired(t => t.Address)
                .WithMany()
                .HasForeignKey(t => t.AddressId);
        }

Database creating and the inserting address with a customer should be like below:

    static void Main(string[] args)
            {
                using (var ctx = new CustomerContext())
                {
                    //ctx.Database.Create(); // This command can be used to create the database using the code first class
                    ctx.CustomerAddresses.Add(new CustomerAddress
                    {
                        AddressType = new AddressType
                        {
                            AddressTypeId = 1,
                            AddressTypeDescriptiom = "Test"
                        },
                        Customer = new Customer
                        {
                            CustomerId = 1,
                            FirstName = "Customer 1"
                        },
                        Address = new Address
                        {
                            Line1 = "Line 1",
                            City = "USA"
                        },
                        DateFrom = DateTime.Now,
                        DateTo = DateTime.Now
                    });

                    ctx.SaveChanges();
                }
            }

Connection string should like below:

    <connectionStrings>
        <add name="DBConnectionString"
            connectionString="Data Source=(local);Initial Catalog=CustomerDB;Integrated Security=true"
            providerName="System.Data.SqlClient"/>
      </connectionStrings>

Please note following note the above code need following references.

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

I tried this and it works as you expected. Please let me know whether you need a sample project on this.

Hope this helps you.

EDITED:

To configure self reference in code first please do as below:

public class Product
    {
        [Key]
        public int ProductId { get; set; }

        public int? ParentProductId { get; set; }

        public virtual Product ParentProduct { get; set; }
    }

Add the following code lines in OnModelCreating method:

modelBuilder.Entity<Product>().HasKey(m => m.ProductId);
modelBuilder.Entity<Product>().
                HasOptional(e => e.ParentProduct).
                WithMany().
                HasForeignKey(m => m.ParentProductId);
  1. For the Employee Table, You Can create a class (Employee.cs):

    public class Employees {

    public string FName {get;set;} public string LName {get;set;} public string Position {get;set;} public string Email {get;set;} [Display(Name = "Full Name")] public string FullName { get { return LName + ", " + FName; } }

}

  1. For the insert, You can do :

      var users = new List<User> { new User{FName ="Chris", LName ="Fajardo",Position=@"Dev",Email="test.test@test.ae"} }; users.ForEach(s => context.User.Add(s)); context.SaveChanges(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM