尝试在 EF Core 中根据 ID 移除项目。

huangapple go评论69阅读模式
英文:

Trying to remove item based on ID in EF Core

问题

以下是翻译好的部分:

我的目标是根据ID删除一项。以下是我当前的代码:

public async Task<IActionResult> RemoveTodoItem(int id)
{
    // TODO
    // 使用EFCore根据ID删除项

    var todoItem = await _context.TodoItems.FindAsync(id);

    if (todoItem == null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(todoItem);
    await _context.SaveChangesAsync();

    return NoContent();
}

我的问题是`TodoItems`一直返回错误代码CS1061,表示`TodoContext`不包含`TodoItems`的定义。

以下是我在`TodoContext`中的代码:

public class TodoContext: DbContext
{
    public DbSet<Todo> Todos { get; set; }

    public TodoContext(DbContextOptions<TodoContext> options) : base(options) {   }
}

`Todo`类:

public class Todo
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsComplete { get; set; }
}

我不确定这是否与依赖注入有关?我相信数据库已经被注入到控制器中。

希望这对你有所帮助。如果你有任何其他问题,请随时提出。

英文:

My goal is to remove an item based on the ID. Here is the code I currently have:

public async Task&lt;IActionResult&gt; RemoveTodoItem(int id)
{
    // TODO
    // Use EFCore to remove the item based on id

    var todoItem = await _context.TodoItems.FindAsync(id);

    if (todoItem == null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(todoItem);
    await _context.SaveChangesAsync();

    return NoContent();
}

My issue is that TodoItems keeps returning the error code CS1061, saying TodoContext does not contain a definition of TodoItems.

Here is the code I have in TodoContext:

public class TodoContext: DbContext
{
    public DbSet&lt;Todo&gt; Todos { get; set; }

    public TodoContext(DbContextOptions&lt;TodoContext&gt; options) : base(options) {   }
}

Todo class:

public class Todo
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsComplete { get; set; }
}

How could I fix this error?

I'm not sure if this has to do with dependency injection? I believe the database has already been injected to the controller.

答案1

得分: 1

> 我的问题是TodoItems 一直返回错误代码CS1061
> 提到 TodoContext 没有定义 TodoItems 的定义。

实际上,您可能因多种原因而出现错误。例如,如果您没有在调用控制器时不初始化TodoContext,或者如果您在命名中写错了拼写错误

另外,如果您没有在表或POCO类上设置主键,或者在初始化builder.Services.AddDbContext时未传递正确的dbContextprogram.cs文件,也可能会导致此问题。

> 我不确定这是否与依赖注入有关?我相信数据库已经被注入到控制器中。

尽管如此,您没有分享完整的控制器类以及构造函数。因此,我已尝试按照您的代码片段以及以下方式进行操作,一切都按预期工作。请查看是否已经按照相同的方式实现了。

模型:

public class Todo
{
    [Key]
    public int Id { get; set; }

    public string? Name { get; set; }

    public bool IsComplete { get; set; }
}

DbContext:

public class TodoContext : DbContext
{
    public TodoContext(DbContextOptions&lt;TodoContext&gt; options) : base(options)
    {
    }

    public DbSet&lt;Todo&gt; TodoItems { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Todo&gt;().ToTable(&quot;TodoItems&quot;);
    }
}

注意: 我在数据库中将表名设置为TodoItems

Program.cs 文件:

var connectionString = builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;);
builder.Services.AddDbContext&lt;TodoContext&gt;(x =&gt; x.UseSqlServer(connectionString));

注意: 请确保您在appsettings.json文件中配置了数据库和服务器名称。

控制器:

public class TodoController : Controller
{
    private readonly TodoContext _context;

    public TodoController(TodoContext context)
    {
        _context = context;
    }

    [HttpDelete]
    public async Task&lt;IActionResult&gt; RemoveTodoItem(int id)
    {
        var todoItem = await _context.TodoItems.FindAsync(id);
        _context.TodoItems.Remove(todoItem);
        await _context.SaveChangesAsync();
        return NoContent();
    }
}

注意: 请确保您在控制器构造函数中初始化了TodoContext。显然,错误指向这一点,或者请检查是否正确拼写了名称。

输出:

尝试在 EF Core 中根据 ID 移除项目。

注意: 如果您想要了解更多关于删除或移除项目的详细信息,您可以在这里查看我们的官方文档

英文:

> My issue is that TodoItems keeps returning the error code CS1061.
> Saying TodoContext does not contain a definition of TodoItems

Actually, you might get the error for numerous reasons. For instance, if you don't initialize the TodoContext while your controller being called. Even, if you write the name with typos.

In additional, if you don't set primary key on your table or POCO class or if correct dbContext has not been passed while initialize the builder.Services.AddDbContext within your program.cs file these also can cause the issue.

> I'm not sure if this has to do with dependency injection? I believe
> the database has already been injected to the controller.

Although, you haven't shared your full controller class along with your constructor. Thus, I have tried following way along with your code snippet and its working as expected. Please have a look if you have implemented the same way.

Model:

public class Todo
{
    [Key]
    public int Id { get; set; }

    public string? Name { get; set; }

    public bool IsComplete { get; set; }
}

DbContext:

public class TodoContext: DbContext
{
    public TodoContext(DbContextOptions&lt;TodoContext&gt; options) : base(options)
    {
    }
       
    public DbSet&lt;Todo&gt; TodoItems { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity&lt;Todo&gt;().ToTable(&quot;TodoItems&quot;);
    }
}

Note: I have set the table name as TodoItems in database.

Program.cs file:

var connectionString = builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;);
builder.Services.AddDbContext&lt;TodoContext&gt;(x =&gt; x.UseSqlServer(connectionString));

Note: Be sure, you have configure your database and server name in your appsettings.json file.

Controller:

public class TodoController : Controller
{
    private readonly TodoContext _context;

    public TodoController(TodoContext context)
    {
        _context = context;
    }
       
    [HttpDelete]
    public async Task&lt;IActionResult&gt; RemoveTodoItem(int id)
    {
        var todoItem = await _context.TodoItems.FindAsync(id);
        _context.TodoItems.Remove(todoItem);
        await _context.SaveChangesAsync();
        return NoContent();
    }
}

Note: Make sure you have initialize the TodoContext within your controller constructor. Apparently, the error pointing this or please check if you have type the name correctly.

Output:

尝试在 EF Core 中根据 ID 移除项目。

Note: If you would like to know more details on Delete or Removing items you could check our official document here

huangapple
  • 本文由 发表于 2023年3月1日 09:32:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定