繁体   English   中英

使用实体框架在创建新实体时向数据库中的现有表添加新记录

[英]Add a new record to existing table in the database on a new entity creation using Entity Framework

我正在使用ASP.NET MVC 3和Entity Framework创建网站。 我想基于以下代码创建数据库:



    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;}
    }

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

问题:就我而言,是否可以使用Entity Framework Code首先通过添加继承Document实体的新实体来更新数据库,并在创建实体时向现有DocumentType表中添加新记录( 而不删除数据库 )? 添加新实体时要实现的所有功能-在DocumentType表中添加新记录,以便该表数据始终是最新的。

如果有可能实现,您能否共享一些链接或带来一些代码示例?

预先感谢您的帮助。

好吧,但是...我不确定您是否真的想要。

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

挑战在于,如果您创建一个新实体,EF必须能够将该新实体存储在数据库中,因此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的表格,其中包含以下列:

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

如果您插入“新闻”和“非新闻”,则在此表中将获得两行,其中“辨别器”列中将包含单词“ News”,而另一行中将包含单词“ NotNews”。

现在,如果您现在添加

public class BreakingNews : Document
{
}

并插入其中的一个,则数据库将不再需要删除并重新创建,你会得到一个新行,在鉴别列单词“BreakingNews”。

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

正如我在顶部所说的那样,您可以执行此操作,但是我不确定这是一个好主意。 当我刚开始使用EF时,我是在做继承的工作,但由于其中的很多内容都给我带来了很多问题,所以我没有做很多。

暂无
暂无

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

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