简体   繁体   English

实体框架在运行时创建多个表 C#

[英]Entity Framework create multiple tables at runtime C#

I try to get familiarized with EF using Sqlite.我尝试使用 Sqlite 来熟悉 EF。

I managed to create a model and based on that model using migrations I created a table.我设法创建了一个 model 并基于该 model 使用迁移创建了一个表。

My question is how I can create multiple tables of same model?我的问题是如何创建相同 model 的多个表?

Example of model: model 示例:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Example of my application db context:我的应用程序数据库上下文示例:

public class ApplicationDbContext:DbContext
{
    public string DbPath { get; private set; }

    public DbSet<Blog> Blogs { get; set; }

    public ApplicationDbContext()
    {
        DbPath = $"HelloBlog.db";
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
       => options.UseSqlite($"Data Source={DbPath}");

}

My question is how can I add new tables at runtime, ex.我的问题是如何在运行时添加新表,例如。 Blog_{Date} ? Blog_{Date}

Since I don't know in advance how many tables I will create.因为我事先不知道我将创建多少张表。

My question is how can I add new tables at runtime, ex.我的问题是如何在运行时添加新表,例如。 Blog_{Date}?博客_{日期}? Since I don't know in advance how many tables I will create.因为我事先不知道我将创建多少张表。

Your data management approach is flawed;您的数据管理方法有缺陷; you're using a table name to store data that should be stored in a column您正在使用表名来存储应该存储在列中的数据

Have a PostedDate column or similar in your Blogs table, store whatever data you were going to encode into the table name, into the column instead.在您的 Blogs 表中有一个 PostedDate 列或类似的列,将您要编码到表名中的任何数据存储到列中。 Index the column索引列

Whatever you were thinking of doing before like:无论您之前想做什么,例如:

SELECT * FROM Blog_2000_01_01
SELECT * FROM Blog_2000_01_02

Ought to be done like:应该这样做:

SELECT * FROM Blog WHERE PostedDate = '2000-01-01'
SELECT * FROM Blog WHERE PostedDate = '2000-01-02'

In EF terms it's hence:因此,在 EF 术语中是:

context.Blog.Where(b => b.PostedDate == new DateTime(2000,1,1))
context.Blog.Where(b => b.PostedDate == new DateTime(2000,1,2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM