Where to create MySql tables ServiceStack & OrmLite

I am just wondering about when and where tables should be created for a persisted application. I have registered my database connection factory in Global.asax.cs:

container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(conn, MySqlDialectProvider.Instance));

I also understand that I need to use the OrmLite API to create tables from the classes I have defined. So for example to create my User class:

    public class User
    {
        [AutoIncrement]
        public int Id { get; set; }

        public string Name { get; set; }

        [Index(Unique = true)]
        public string Email { get; set; }

        public string Country { get; set; }

        public string passwordHash { get; set; }

        public DateTime Dob { get; set; }

        public Sex Sex { get; set; }

        public DateTime CreatedOn { get; set; }

        public Active Active { get; set; }
    }

I would execute the following:

Db.CreateTable<User>(false);

I have a lot of tables that need to be created. Should I create a separate class that first created all my tables like this or execute that in each rest call to UserService .

Also is it possible to create all my tables directly in my database, naming each table with its corresponding class, and then Orm would match classes to existing tables automatically?

Sorry this has me a bit confused. Thanks for any help you can give me.


is it possible to create all my tables directly in my database, naming each table with its corresponding class, and then Orm would match classes to existing tables automatically?

You don't have to use OrmLite to create tables. If the table(s) already exist in your MySQL database (or you want to create using MySQL interface) you will be able to access them as long as the class name is the same as the table name. If table names don't match the class names, use the Alias attribute

[Alias("Users")] //If table name is Users
public class User
{
    public int Id {get;set;}
}

I wouldn't create the tables in your services. Generally, I would do it in AppHost.Configure method which is run when the application starts. Doing this will attempt to create the tables every time your application is started (which could be once a day - see here) so you might want to set a flag in a config file to do a check for creating the tables.


I would create them in the AppHost.Configure() which is only run by a single main thread on Startup that's guaranteed to complete before any requests are served.

If you wanted to you can automate this somewhat by using reflection to find all the types that need to be created and calling the non-generic API versions:

db.CreateTable(overwrite:false, typeof(Table1));
db.CreateTable(overwrite:false, new[] { typeof(Table1), typeof(Table2, etc });
链接地址: http://www.djcxy.com/p/65964.html

上一篇: ServiceStack.Text错误地使用空条目反序列化Array

下一篇: 在哪里创建MySql表ServiceStack&OrmLite