entity framework code first and database user - entity-framework-4.1

We're running into a small problem deploying a web application to another environment.
We created the application's db using Entity Framework Code First approach (db automatic created from Model).
In this development environment, we are using integrated security and the tables are created under the dbo user. The tables are like
[dbo].[myTable]
For our other environment, we are using username/password authentication for the DB.
We scripted the tables and created them on the DB. So they are now named like
[myDbUser].[myTable]
When running the application, we encounter always the problem
Invalid object name 'dbo.myTable'.
Seems like the code is still trying to look for a dbo table, which is not present and thus fails.
Can anyone shed some light on this problem? Where does Entity Framework gets this dbo prefix from?
Thanks

Specify schema explicitly:
[Table("Users", Schema = "dbo")]
public class User { .. }
Or specify default db schema for your user - 'dbo'

To specify schema in fluent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<ClassName>().ToTable("TableName", "SchemaName");

I ran into this issue recently as well as we support several different schemas with the same model. What I basically came up with was the passing the schema name to the classes/methods that map the model. So for example, EntityTypeConfiguration subclasses take the schema name as a constructor argument, and pass it along with the hard-coded string to ToTable().
See here for a more detailed explanation: https://stackoverflow.com/a/14782001/243607

Related

Yii2 MySQL table names and HTTP404 errors

I am new to the Yii technology, but having worked in IT for many years I hoped I understood generally how software is designed. But the Yii guys have got me good.
I have been trying to understand why I am getting HTTP404 errors.
I have a Win 10 environment using MySQL, with latest versions of MySQL and PHP. I naively assumed that Yii would support the nomenclature standards for objects in the MySQL, especially table names. However it appears I am wrong, so here is a heads up for those interested.
I use all lower case characters for my table names, and where I have a table that is a link between two entities I use a name such as entity1_entity2. I use gii to generate a model from this table and the the CRUD option to generate a basic initial application.
I have the pretty URL active, so the initial URL I use is :
\localhost\Movies\movieactor
Where Movies is the website name defined to IIS (virtual directory) and movieactor is the lowercase name I used for the model and controller objects. The actual name prefix I used was MovieActor for the model and controller objects. I used movieactor for the view sub-directory.
Much to my surprise I was presented with an HTTP404 error message. I spent most of a day trying to understand what I had done wrong.
After a good sleep, I started again the next morning. I decided to try changing the name of the relevant table from movie_actor to movieactor. I then regenerated the model, and CRUD components. This time when I invoked the same URL I was pleasantly surprised to see the web application show me the data.
I have no idea what restrictions the Yii guys place on table names, no documentation that I can find, but this is my experience, and hopefully it may save others some grief.
Have I missed something or is my story correct ?
First of all in Yii there are no requirements for table names. Table or model class names are not directly related to URLs.
When you are using gii to generate model you are prompted to enter the table name. Then the model name is suggested as pascal case version of table name. For example if your table is named movie_actor the suggested model class name will be MovieActor. But you don't have to accept that, you can change it to whatever you want.
Then when you are generating CRUD it asks you to enter model class, search model class and controller class. The model class here is the MovieActor generated earlier. Search model class can be whatever you like, but what is important for URL is the controller class. There is something called controller id based on controller class name. It's a kebab case version of controller class name after removing the Controller suffix. If you name your controller as MovieActorController its controller id will be movie-actor. It's this controller id that you need to use in your url to reach that controller. So, url you have to use for this controller would be \localhost\Movies\movie-actor. You need to use same controller id as a sub-directory for your views too.
When you've decided to change table name to movieactor you've probably also generated the controller as MovieactorController. Because of that its id was movieactor and your url and views subfolder were correct.

Not able to use built-in models i.e. "user", error: no response from server

I have created many models in loopback for my project. And use these models with the help of "http://localhost:3000/explorer" in my browser.
These model API's are working fine. But, whenever I tried to use built-in models i.e "user" from the explorer. I got the below error:
and in the terminal. I got the below error. And terminal command automatically terminates.
I am new in the loopback. Why am I not able to use built-in models "user".
Please, help me.
Thanks in advance.
To anyone else that encounters this, I ran into this today and found this question unanswered, so I will do my best to give my explanation and findings here.
The error, roleModel.isInRole is not a function, means simply that the role model does not have a function called isInRole.
In my case, this was because another model was automatically generated from an existing database table called Role, which overrode the internal Role model of Loopback.
When the internal Role model is overridden, the isInRole function is not inherited automatically and will result in the above error.

Connect J2EE application with two different databases

I am developping J2EE application with appfuse that have default settings with mySQL
<!-- Database settings -->
<dbunit.dataTypeFactoryName>org.dbunit.ext.mysql.MySqlDataTypeFactory</dbunit.dataTypeFactoryName>
<dbunit.operation.type>CLEAN_INSERT</dbunit.operation.type>
<hibernate.dialect>org.hibernate.dialect.MySQL5InnoDBDialect</hibernate.dialect>
<jdbc.groupId>mysql</jdbc.groupId>
<jdbc.artifactId>mysql-connector-java</jdbc.artifactId>
<jdbc.version>5.1.27</jdbc.version>
<jdbc.driverClassName>com.mysql.jdbc.Driver</jdbc.driverClassName>
<jdbc.url>jdbc:mysql://localhost/${db.name}?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true</jdbc.url>
<jdbc.username>root</jdbc.username>
<jdbc.password></jdbc.password>
<jdbc.validationQuery>SELECT 1 + 1</jdbc.validationQuery>
But i need to connect my application with external database (SQL QERVER)to retreive some data.
I need help to configure maven to use two different database (mysql +sql server)
maven will help you out with loading of the driver jar files. You would be creating two data source / session factory to achieve this.
I think this can be achieved quite easily in a brief guideline as follows:
Create a second "dataSource" bean definition in applicationContext-resources.xml with MSSQL specific values such as driver class, url etc. Give it a different bean id, "dataSourceMSSQL" perhaps. Bind them up to different properties file if you don't want to hard coded property values. For simplicity you can just hard coded it (not recommended). If you chose otherwise, you need to create another properties file to store mssql connection properties, perhaps jdbc-mssql.properties and add it into propertyConfigurer list. This also require you to make changes to your pom file to include custom settings under <!-- Database settings --> section. This can be a bit complicated.
Create another "sessionFactory" bean definition in applicationContext-dao.xml with MSSQL specific values such as hibernate dialect etc. and binds it to "dataSourceMSSQL" as dataSource property ref. Give it a different bean id perhaps, "sessionFactoryMSSQL".
Wire your DAOs which require the new sessionFactory i.e.:
#Autowired private SessionFactory sessionFactoryMSSQL;
Hope that will work for you.

Change Entity Framework database schema map after using code first

I've finished building my blog using EF and Code First.
EF was running against my local SQL Express instance, with [DBO] schema.
Now i want to publish the blog, and i have done the following :
Generetade the scripts for the tables and all objects from SQL Express and change [dbo] to my [administrator] schema from my server.
Ran the scripts against the server. No issues, all objects were created an populated just fine.
I have modified Webconfig and added my BlogContext connection string to point to the server not local sql express.
Published the site.
The error i am getting is : Invalid object name 'dbo.Articles'. - where Articles is one of my entities. It resides on my sql server, [Administrator].Articles.
As far as i can tell EF still thinks im using the DBO schema. Although i have added the connection string to point to administrator user.
How can i change the schema that EF thinks it should use?
EF will use dbo schema if you didn't configure the schema explicitly through data annotations or fluent API.
[Table("MyTable", "MySchema")]
public class MyEntity
{
}
Or
modelBuidler.Entity<MyEntity>().ToTable("MyTable", "MySchema");
Just for searchers: I am just working with EF5 .NET4.5, and
[Table("MyTable", "MySchema")]
does not work. Even if VS2012 shows there is an overload which takes 2 parameters, on build it gives the error: 'System.ComponentModel.DataAnnotations.Schema.TableAttribute' does not contain a constructor that takes 2 arguments.
But the code mapping works just fine.

Entity Framework 4 Code First - Prevent DB Drop/Create

I've written an ASP.Net MVC 3 application using the Code First paradigm whereby when I make a change to the model the Entity Framework automatically attempts to re-create the underlying SQL Server Database via DROP and CREATE statements. The problem is the application is hosted on a 3rd party remote server which limits the number of databases I can have and does not seem to allow me to programmatically execute "CREATE DATABASE..." statements as I gather from this error message:
CREATE DATABASE permission denied in database 'master'.
Is there any way to stop the Entity Framework from dropping and attempting to re-create the whole database and instead make it simply drop the tables and re-create them?
After creating the database manually and running the application I also get the following error I guess as the Entity Framework tries to modify the database:
Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.
UPDATE: Found this gem through google, it sounds like its exactly what you need: http://nuget.org/Tags/IDatabaseInitializer
You can use a different database initializer. Lets say your context is called SampleContext then your constructor would look like this:
public SampleContext()
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<SampleContext>());
}
Note that the above is the default initializer. You will probably need to create your own custom initializer by implementing IDatabaseInitializer. Theres some good info here: http://sankarsan.wordpress.com/2010/10/14/entity-framework-ctp-4-0-database-initialization/
Using EF 4.3 with Migrations you do not get this behavior - at least I have not seen it. But I also have this set in my code -
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}