S
S
sergeyfk2017-12-05 18:57:43
SQLite
sergeyfk, 2017-12-05 18:57:43

How to create a database using LINQ?

How to create a database with multiple tables?
So far I have only been able to write this

SQLiteConnection connection = new SQLiteConnection();
            connection.ConnectionString = (String.Format("Data Source = {0}; Vesion = 3;", savepath));
            DataContext db = new DataContext(connection);

Well, immediately how to add FOREIGN KEY when creating a database.
For clarity, I will ask you to make such an example. So I create a table with these commands
RunCommand(@"CREATE table [menu] (
                        [id] integer PRIMARY KEY AUTOINCREMENT NOT NULL,
                        [name] varchar(100) NOT NULL
                        ); ");
            RunCommand(@"CREATE table [sub_menu] (
                         [id] integer PRIMARY KEY AUTOINCREMENT NOT NULL,
                        [name] varchar(100) NOT NULL,
                        [owner_menu_id] integer NOT NULL,
                        FOREIGN KEY (owner_menu_id)
                        REFERENCES menu (id)
                        ON UPDATE CASCADE
                        ON DELETE CASCADE
                        );");

Well, keep almost ready-made classes to write less:
[Table(Name = "Menu")]
    public class Menu
    {
        [Column(Name = "Id", CanBeNull = false, IsPrimaryKey = true, DbType = "int PRIMARY KEY AUTOINCREMENT NOT NULL", IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int Id { get; set; }

        [Column(Name = "Name", CanBeNull = false, DbType = "varchar(100) NOT NULL")]
        public string Name { get; set; }
    }

[Table(Name = "SubMenu")]
    public class SubMenu
    {
        [Column(Name = "Id", CanBeNull = false, IsDbGenerated = true, DbType = "int PRIMARY KEY AUTOINCREMENT NOT NULL", AutoSync = AutoSync.OnInsert)]
        public int Id { get; set; }

        [Column(Name = "Name", CanBeNull = false, DbType = "varchar(100) NOT NULL")]
        public string Name { get; set; }

        [Column(Name = "OwnerMenuId", CanBeNull = false, DbType = "int NOT NULL")]
        public string OwnerMenuId { get; set; }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2017-12-05
@sergeyfk

Wow, even ready-made classes to write less? Well, at least thanks for that))
p/s there are ready-made classes - use the Code-First approach. No Raw Sql commands needed.
For EF:
https://msdn.microsoft.com/en-us/library/jj193542(...
https://metanit.com/sharp/entityframework/1.2.php
For EF Core
https://docs.microsoft. com/en-us/ef/core/get-start...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question