zoukankan      html  css  js  c++  java
  • 3. 创建模型

    概念: EF Core 可以从/向 数据库中读取和写入实体实例,如果使用的是关系型数据库,EF Core 可以通过迁移为实体创建表

    在模型中包含类型

    按照约定,在上下文中的DbSet属性中公开的类型作为实体包含在模型中,还包含在OnModelCreating方法中指定的实体类型,就像通过递归方式浏览其它实现的实体类型的导航属性找到的任何类型一样。

    在下面的代码示例中,包含了所有类型:

    • Blog 包含在内,因为它在上下文的 DbSet 属性中公开。
    • 包含 Post 是因为它是通过 Blog.Posts 导航属性发现的。
    • AuditEntry,因为它是在 OnModelCreating中指定的。
    class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AuditEntry>();
        }
    }
    
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    
        public List<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    
        public Blog Blog { get; set; }
    }
    
    public class AuditEntry
    {
        public int AuditEntryId { get; set; }
        public string Username { get; set; }
        public string Action { get; set; }
    }

    表架构

    使用关系数据库时,表按约定在数据库的默认架构中创建。 例如,Microsoft SQL Server 将使用 dbo 架构(SQLite 不支持架构)。

    你可以配置要在特定架构中创建的表,如下所示:

    //注释模式
    [Table("blogs", Schema = "blogging")]
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
    
    //API 模式
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .ToTable("blogs", schema: "blogging");
    }
    

    您还可以在模型级别定义 Fluent API 的默认架构,而不是为每个表指定架构:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("blogging");
    }

    请注意,设置默认架构也会影响其他数据库对象,如序列。

  • 相关阅读:
    DIV切换
    打开文件
    修改config配置文件
    soapui安装和破解教程
    URL文件保存到本地
    业务gis 怎么让别的开发人员不需要懂gis就可以搞开发? (三)
    业务gis 怎么让别的开发人员不需要懂gis就可以搞开发? (二)
    业务gis 怎么让别的开发人员不需要懂gis就可以搞开发? (一)
    合并的地块带有小缝隙怎么办
    flex polygon 序列化为txt 文本
  • 原文地址:https://www.cnblogs.com/maanshancss/p/13360355.html
Copyright © 2011-2022 走看看