简体   繁体   中英

Creating a database with linq2db

I am writing a small program to test out linq2db. What I want to do is create the database if it does not already exist. Most(all?) of the linq2db documentation assumes an existing database. I check if the database exists and if not create an empty database using CreateCommand as below. The Intellisense for this says this method is "For internal use only". Is it OK to use CreateCommand or is there a better way?

namespace SqliteTest
{
    public partial class ImageDatabaseDB : LinqToDB.Data.DataConnection
    {
        public ITable<testTable> testTables { get { return this.GetTable<testTable>(); } }

        public void InitMappingSchema()
        {
        }
        public ImageDatabaseDB()
        {
            InitDataContext();
            InitMappingSchema();
        }
        public ImageDatabaseDB(string configuration) : base(configuration)
        {
            InitDataContext();
            InitMappingSchema();
        } 
        partial void InitDataContext();
    }
    [Table("testTable")]
    public partial class testTable
    {
        [PrimaryKey, Identity] public int id;
        [Column, NotNull] public string Name;
        [Column, Nullable] public string Description;
    }
    public static partial class TableExtensions
    {
        public static testTable Find(this ITable<testTable> table, long id)
        {
            return table.FirstOrDefault(t =>
                t.id == id);
        }
    }
class Program
{
    static void Main(string[] args)
    {
        const string dbLocation = @".\TestDatabase\TestDatabase.sqlite";
        if (!File.Exists(dbLocation))
        {
            using (var db = new TestDatabaseDB())
            {
                db.CreateCommand(); 
                // create tables...
            }
        }

    }

要创建sqlite数据库,您应该使用LinqToDB.DataProvider.SQLite.SQLiteTools.CreateDatabase(...)方法

Linq2db offers Database First approach only , creating DB schema from entity mappings (Code First approach) is not supported out-of-the-box.

However, Linq2db is able to generate CREATE TABLE DDL statements from mappings by IDataContext.CreateTable<T> . See also this discussion .

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