简体   繁体   English

使用Entity Framework进行原始查询以添加/更改表的列而不进行迁移

[英]Raw query to add/alter column of table using Entity Framework without migration

I have restricted access to SQL server database & I have to alter table from my MVC project. 我对SQL Server数据库的访问受到限制,并且必须更改MVC项目中的表。 I have tried: 我努力了:

var db = MyDbContext.Create();
try
{
    var res =
    db.Speakers.SqlQuery("ALTER TABLE [dbo].[Speakers] ADD [LastName] [nvarchar](256) NULL");
}
catch (Exception exception)
{
    Console.WriteLine(exception);
}

its not throwing exception but not updating table. 它不会抛出异常但不会更新表。 I have no idea whether Raw query allow alteration or not. 我不知道原始查询是否允许更改。 But I just gave a try. 但是我只是尝试了一下。 Can any one tell how can I alter database? 谁能告诉我如何更改数据库?

Non-query commands can be sent to the database using the ExecuteSqlCommand method on Database. 可以使用数据库上的ExecuteSqlCommand方法将非查询命令发送到数据库。 For example: 例如:

 using (var context = new BloggingContext()) { context.Database.ExecuteSqlCommand( "UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1"); } 

Note that any changes made to data in the database using ExecuteSqlCommand are opaque to the context until entities are loaded or reloaded from the database. 请注意,使用ExecuteSqlCommand对数据库中的数据所做的任何更改对于上下文都是不透明的,直到从数据库加载或重新加载实体为止。

Entity Framework Raw SQL Queries https://msdn.microsoft.com/en-gb/data/jj592907.aspx 实体框架原始SQL查询https://msdn.microsoft.com/en-gb/data/jj592907.aspx

Try this approach: 试试这个方法:

    db.Database
.ExecuteSqlCommand("ALTER TABLE [dbo].[Speakers] ADD [LastName] [nvarchar](256) NULL");

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

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