【问题标题】:Add a new record to existing table in the database on a new entity creation using Entity Framework在使用实体框架创建新实体时向数据库中的现有表添加新记录
【发布时间】:2011-09-15 14:09:36
【问题描述】:

我正在使用 ASP.NET MVC 3 和实体框架制作网站。我想根据以下代码创建一个数据库:



    public abstract class Document
    {
       public int DocId {get; set;}
       public DocumentType DocType {get; set;}
       public DateTime DateCreated {get; set;}
       public DateTime DateUpdated {get; set;}

    }

      public class DocumentType{
      public int TypeId {get; set;}
      public int TypeName {get; set;}
    }


    public class News: Document
    {
       public string Title {get; set;}
       public string Body {get; set;}
    }

简短说明: 文档是诸如新闻(和其他)等内容类型的基础实体。新闻继承文档。每个文档(如新闻)都有其文档类型。例如,News 的类型名为“News”。

问题: 在我的情况下,是否可以通过添加继承 Document 实体的新实体并在创建实体时将新记录添加到现有 DocumentType 表(不删除数据库)来使用 Entity Framework Code First 更新数据库? 当我添加一个新实体时,我想要实现的所有目标 - 要在 DocumentType 表中添加一条新记录,以便此表数据始终是最新的。

如果可以实现,能否分享一些链接或者带来一些代码示例?

提前感谢您的帮助。

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 entity-framework


    【解决方案1】:

    嗯,有点……但我不确定你是否真的想要。

    问题不在于 DocumentType,它只是数据库中的一条记录,您可以在该表中插入更多记录。所以,我忽略了它的那一面(它只是一个代码表)。

    挑战在于,如果您创建一个新实体,EF 必须能够将该新实体存储在数据库中,因此它可能应该为它创建一个表或其他东西,因此数据库需要更改。 EF(当前)不支持更改数据库,因此会提示您删除并创建数据库。现在,只要新实体具有完全相同的字段,您就有一种方法可以做到这一点。

    首先让我解释一下,EF 处理继承的 默认 方式是在 Documents 表中有一个 discriminator 列来确定此特定对象的类型行是。这不是唯一的方法,我强烈建议您在开始继承之前查看http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx 以充分理解这一点。有一些丑陋的陷阱,包括在某些地方,当您使用继承时,EF 确实没有按照您的预期行事。

    无论如何,给定这些类:

    public abstract class Document
    {
        public int ID { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateUpdated { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    
        public Document()
        {
            DateCreated = DateTime.UtcNow;
            DateUpdated = DateTime.UtcNow;
        }
    }
    
    public class News : Document
    {
    }
    
    public class NotNews : Document
    {
    }
    

    还有这个 Db 上下文

    class MyContext : DbContext
    {
        public DbSet<Document> Documents { get; set; }
    }
    

    您最终会得到一个名为 Documents 的表格,其中包含以下列:

    • 身份证
    • 创建日期
    • 更新日期
    • 标题
    • 身体
    • 鉴别器

    如果您插入一个 News 和一个 NotNews,那么您会在此表中获得两行,其中一个将在 Discriminator 列中包含单词“News”,另一行将包含单词“NotNews”。

    现在,如果你现在添加

    public class BreakingNews : Document
    {
    }
    

    并插入其中一个,然后数据库将不需要删除并重新创建,您将在鉴别器列中获得一个带有单词“BreakingNews”的新行。

    所以,它有效。但是,如果您向任何新类添加任何新属性,则需要更改数据库。我相信即使覆盖也可能需要更改数据库,但您可以轻松地进行测试。

    正如我在顶部所说的 - 你可以这样做,但我不确定这是一个好主意。当我第一次开始使用 EF 时,我正在做一些关于继承的事情,但我已经撤消了大部分它,因为它只会在我的经验中导致太多问题。

    【讨论】:

      猜你喜欢
      • 2018-08-24
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多