locked
Using Code First for database that already has database first approach used in the application RRS feed

  • Question

  • User-316692755 posted

    Hi, I am new to the "code first" approach as i have been using database first untill now. 

    I have been working on a project with a couple of my friends using .net MVC. We have all been using database first, and created quite large EDMX structure, which at this point is very complex, and to be honest every single update requires quite the effort. 

    That is why, when i started to work on one of the sub-modules i wanted to try something else, and the code first seemed like a good way to go.

    I have create a new connection string that points to the same database, . My issue is that, when i try to use models that are already used in the db first, i face an error that this class already exists. So i have attpemted to change the name of my code first models with some prefix CF_tablename for example. I have pointed those classes to the proper table name like" [Table("tablename")] " And it seemed to work. However when i try to add a migration now, code first see this as i am attempting to rename those tables...

    So my question is, is it ok to use both code first approach and database approach when pointing to the same database ? How can i avoid trying to rename the table name. And do you know of any paid or free courses that gives comperhensive knowlage about Code first approach, not just guide for how to use it with clean application and new database ?

    Thursday, September 13, 2018 8:34 AM

All replies

  • User1120430333 posted

    I have been working on a project with a couple of my friends using .net MVC. We have all been using database first, and created quite large EDMX structure, which at this point is very complex, and to be honest every single update requires quite the effort.

    I find that hard to believe. I have used EF DB first with a database schema over 100 tables in updating the model from the database schema and the whole nine yards with very little problems.  

    So my question is, is it ok to use both code first approach and database approach when pointing to the same database ? How can i avoid trying to rename the table name. And do you know of any paid or free courses that gives comperhensive knowlage about Code first approach, not just guide for how to use it with clean application and new database ?

    It's called namespace seperation. You make a "New Folder" in the project and create the EF Virtual Object Model in the folder, which gives you namespace  seperation between code. Both EF models DB first and code first should be in their own project folders. .

    And checkout Pluralsight for training on .NET technology.

    Thursday, September 13, 2018 10:12 AM
  • User-821857111 posted

    There is tooling to support the generation of POCO entity classes from an existing database. So rather than mix EDMX and Code First, you could go the whole nine yards and migrate the entire project to code first. That would be mu recommendation. 

    Doing this will also result in separate mapping configuration classes being generated for your entities. A lot of them will contain stuff that isn't really necessary, but they will give you good insight into how fluent API configurations should be applied. Perhaps you should try this on a copy (branch) of your project first?

    Thursday, September 13, 2018 10:28 AM
  • User-316692755 posted

    I find that hard to believe. I have used EF DB first with a database schema over 100 tables in updating the model from the database schema and the whole nine yards with very little problems.  

    In our case its not so much a a size issue, but that we kinda broke it at some point.... whenever i try to update the EDMX the first new object will replace one of the exising SP....

    for example if i add three new tables.

    Models will be created in EDMX for second and third table but the first one will update  (not related at all) procedure with the model structure for the first table.... Tried to find a reason, but had no luck so far, and manual updates are pain...

    Anyway i was able to setup code first configuration, seems to be working so far.

    Monday, September 17, 2018 12:06 PM
  • User1120430333 posted

    In our case its not so much a a size issue, but that we kinda broke it at some point.... whenever i try to update the EDMX the first new object will replace one of the exising SP....

    Myself, If I have to use a sproc, then I'll use the EF backdoor. ADO.NET, MS SQL Server Command objects, a sproc and custom object like a DTO.

    Models will be created in EDMX for second and third table but the first one will update (not related at all) procedure with the model structure for the first table.... Tried to find a reason, but had no luck so far, and manual updates are pain...

    I don't know what the would be about other than there could be a relationship involved. You could always remove the relationship  off the model, do the update, and put the relationship back on the model between objects. 

    Monday, September 17, 2018 4:10 PM
  • User475983607 posted

    Models will be created in EDMX for second and third table but the first one will update  (not related at all) procedure with the model structure for the first table.... Tried to find a reason, but had no luck so far, and manual updates are pain...

    That's usually due to not updating the function import.

    Anyway i was able to setup code first configuration, seems to be working so far.

    IMHO, Code First is much easier to deal with.

    Monday, September 17, 2018 4:28 PM
  • User-316692755 posted

    That's usually due to not updating the function import.

    Can you please elaborate what do you mean ?? even though i am switching to code first, i still would like to know why this is happening ??

    Monday, September 17, 2018 4:43 PM
  • User475983607 posted

    Arudian

    Can you please elaborate what do you mean ?? even though i am switching to code first, i still would like to know why this is happening ??

    I cannot see your code but, as stated above, this issue us generally due to forgetting to update the function import.  In EDMX, stored procedures imported as functions.  Part of the import processes creates a complex results model based on the proc's select.  If you skip this step then the result model does not change.

    EDMX function import

    http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx

    Monday, September 17, 2018 5:04 PM
  • User-271186128 posted

    Hi Arudian,

    My issue is that, when i try to use models that are already used in the db first, i face an error that this class already exists. So i have attpemted to change the name of my code first models with some prefix CF_tablename for example. I have pointed those classes to the proper table name like" [Table("tablename")] " And it seemed to work. However when i try to add a migration now, code first see this as i am attempting to rename those tables...

    First, Please refer to the this link to use Code First to an Existing Database.

    After generating the code first context, if we want to add new tables using EF code first, we might meet the table already exist error when enables migration. In this case, you could modify the migration file.

    For example, in my database, there already contains a table Table1, and I have added the EDMX file and generate the Code Fist Context. Then I add a new table (Student) using Code First, when add a migration, it will generate the following class:

    namespace webapps.Migrations
    {
        using System;
        using System.Data.Entity.Migrations;
        
        public partial class AddStudent : DbMigration
        {
            public override void Up()
            {
                CreateTable(
                    "dbo.Students",
                    c => new
                        {
                            StuID = c.Int(nullable: false, identity: true),
                            StuName = c.String(),
                            Age = c.Int(nullable: false),
                        })
                    .PrimaryKey(t => t.StuID);
                
                //CreateTable(
                //    "dbo.Table1",
                //    c => new
                //        {
                //            itemindex = c.Int(nullable: false, identity: true),
                //            id = c.Int(),
                //            product = c.String(maxLength: 50),
                //            expense = c.String(maxLength: 50),
                //            price = c.Int(),
                //        })
                //    .PrimaryKey(t => t.itemindex);
                
            }
            
            public override void Down()
            {
                //DropTable("dbo.Table1");
                DropTable("dbo.Students");
            }
        }
    }
    

    Since, there is already contains the Table1, we could remove the related part of code, then update the database.

    Then, if you want to add the Student table into the EDMX, you could using the "Update Model from DataBase..." option and select the Student table, then when you rebuild the solution, you might meet the class already exists error. In this case, you could use the partial key word or remove one of the class.

    For example:

    namespace webapps
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
    
        public partial class Student
        {
            [Key]
            public int StuID { get; set; }
            public string StuName { get; set; }
            public int Age { get; set; }
        }
    }

    In my opinion, if you want to use Code First and DB First in the application, I think the related tables should be handled separately. For the Code First generated tables, we should use code first approach to manage them, and the database approach generated tables, we could use database first methods to manage them. 

    Here are some resource about EF Code First and Database First, you can refer to them:

    Entity Framework Code First 

    Entity Framework DataBase First

    Best regards,
    Dillion

    Tuesday, September 18, 2018 7:56 AM