Code First vs. Database First

前端 未结 3 1034
别跟我提以往
别跟我提以往 2020-12-30 02:44

I created an Entity Framework model based on an existing database, then generated the POCO entities from the model. The connection string in my web.config isn\'t Entity Fram

相关标签:
3条回答
  • 2020-12-30 02:52

    If the connection string has the metadata, EF thinks it is Model First or Database First. If it is a plain connection string, EF thinks it is Code First. However, if you want to start out doing model first but make EF think you are really doing code first (which is what you are doing), make sure you are using the DbContext code generator, not the default one. Code first POCOs are really that--"plain old c# objects"-- no special database aware or change tracking stuff in them at all. To use the DbContext code generator, right click on your model diagram and choose "Add new code generation item..." then select the ADO.NET DbContext Generator. Also, depending on how you named your primary and foreign keys and/or whether they are more complicated than just simple int IDs, you will probably need to fill in some code to map the relationships between your objects in the "OnModelCreating" method in your context. Delete the line throw new UnintendedCodeFirstException(); and replace it with your mapping code. Otherwise EF may not be able to figure out all the relationships (remember there's no metadata for it to rely on).

    Hope this helps.

    0 讨论(0)
  • 2020-12-30 02:55

    I'm using Database first and resolved this by copying the EDMX generated connection string to the app.config of my startup application. One already existed but apparently they were different

    0 讨论(0)
  • 2020-12-30 03:08

    You need the following in your config file:

    <connectionStrings>
    <add name="<The name of your class>" 
         connectionString="metadata=res://*/<test>.csdl|res://*/<test>.ssdl|res://*/<test>.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=<your source>;initial catalog=<your db>;persist security info=True;user id=<your user id>;password=<your password>;multipleactiveresultsets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
    </connectionStrings>
    
    0 讨论(0)
提交回复
热议问题