如何在Asp.Net中使用数据库迁移创建存储过程

时间:2017-11-21 09:59:15

标签: asp.net entity-framework stored-procedures ef-migrations

我正在使用迁移来创建我的数据库模型。我已经通过覆盖OnModelCreating创建了所有表格。

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder){
modelBuilder.Entity<AccessLevel>().Map(c =>
{
    .ToTable("AccessLevel", "HelpSystem");
    c.Properties(p => new
        {
            p.Id,
            p.Name,
            p.Description
        });
}).HasKey(x => x.Id);
modelBuilder.Entity<AccessLevel>().Property(x => x.Id).HasColumnAnnotation("DatabaseGenerated", DatabaseGeneratedOption.Identity);}

现在我想像这样创建存储过程到我的数据库。我该怎么做?

这是我的存储过程的Sql脚本

CREATE PROCEDURE [HelpSystem].[sp_GetLanguageContentByObject] @InfoObjectId AS BIGINT AS
SELECT  io.Id InfoObjectId ,
io.Name InfoObject ,
cc.Id ComChannelId ,
cc.Name ComChannel ,
cc2.Id ContentCategoryId ,
cc2.Name ContentCategory ,
c.Id ContentId ,
c.Name ContentName ,
c.Description ,
c.AuthorPartyId ,
c.DefaultLanguageId ,
c3.CultureCode DefaultLanguage ,
lc.Id LanguageContentId ,
lc.LanguageId ,
c2.CultureCode Language ,
lc.Title ,
lc.Content FROM    HelpSystem.InfoPointInfoObject ipio
    JOIN HelpSystem.InfoObject io ON io.Id = ipio.InfoObjectId
    JOIN HelpSystem.InfoPointComChannel ipcc ON ipcc.InfoPointId = ipio.InfoPointId
    JOIN HelpSystem.ComChannel cc ON cc.Id = ipcc.ComChannelId
    JOIN HelpSystem.InfoPointContent ipc ON ipc.InfoPointId = ipcc.InfoPointId
    JOIN HelpSystem.Content c ON c.Id = ipc.ContentId
    JOIN HelpSystem.ContentCategory cc2 ON cc2.Id = c.ContentCategoryId
    JOIN HelpSystem.LanguageContent lc ON lc.ContentId = ipc.ContentId
    JOIN Localization.Culture c2 ON lc.LanguageId = c2.Id
    JOIN Localization.Culture c3 ON c.DefaultLanguageId = c3.Id WHERE ipio.InfoObjectId = @InfoObjectId AND (ipio.ExpireDateTime IS NULL OR ipio.ExpireDateTime > GETUTCDATE()) AND (ipcc.ExpiredDateTime IS NULL OR ipcc.ExpiredDateTime > GETUTCDATE()) AND (ipc.ExpiredDateTime IS NULL OR ipc.ExpiredDateTime > GETUTCDATE())

1 个答案:

答案 0 :(得分:2)

您可以使用ExecuteSqlCommand API直接在dbcontext的实例上编写存储过程代码,如下所示:

_dataContext.Database.ExecuteSqlCommand("stored procedure sql");

您还可以使用CreateStoredProcedure函数直接从DbMigration文件创建存储过程。 CreateStoredProcedure API

modelBuilder上有扩展方法,可让您创建存储过程。