gpt4 book ai didi

entity-framework - Entity Framework 核心 : Include many-to-many related objects in WebAPI

转载 作者:行者123 更新时间:2023-12-04 00:37:21 26 4
gpt4 key购买 nike

我不太熟悉 .NET 框架,但决定试用 ASP.NET Core 和 EF Core。我想制作一个非常简单的 Web API 后端,但我在处理多对多关系时遇到了问题。

我知道我需要为这两个实体创建一个关系表,如本文中的示例所示:How to create a many to many relationship with latest nightly builds of EF Core?

我还让我的模型构建器按照此处描述的方式创建关系 http://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many

我的代码是这样的:

在数据库上下文中:

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

builder.Entity<MovieActor>().HasKey(x => new { x.MovieId, x.ActorId});

builder.Entity<MovieActor>()
.HasOne(m => m.Movie)
.WithMany(ma => ma.MovieActors)
.HasForeignKey(m => m.MovieId);

builder.Entity<MovieActor>()
.HasOne(m => m.Actor)
.WithMany(ma => ma.MovieActors)
.HasForeignKey(a => a.ActorId);

}

public DbSet<Movie> Movies { get; set; }

public DbSet<Actor> Actors { get; set; }


}

模型:

namespace Test.Models
{
public class Movie
{
public int MovieId { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Code { get; set; }
public string Path { get; set; }

public ICollection<MovieActor> MovieActors { get; set; }
}

public class Actor
{
public int ActorId { get; set; }
public string Name { get; set; }
public ICollection<MovieActor> MovieActors { get; set; }
}

public class MovieActor
{
public int MovieId { get; set; }
public Movie Movie { get; set; }

public int ActorId { get; set; }
public Actor Actor { get; set; }
}
}

这似乎在大多数情况下都有效。我可以创建新的 MovieActor 对象并将它们添加到数据库中。一件看起来很奇怪的事情是 Movie 和 Actor 模型现在有一个 MovieActors 属性,但它总是 null,尽管连接表有条目。

我想不通的是如何在我的 WebAPI Controller 中检索这些相关对象。我的 Linq 技能很弱,所以也许我只需要复习一下,但我不知道从哪里开始。当我通过 ID 获取电影或获取所有电影的列表时,我希望结果在对象的数组中包含任何相关的 Actors。在另一个方向上也是如此,当获得一个 Actor 时,我想获得一系列他们的电影。

这是我尝试利用这种关系的 Controller 方法之一:

        // POST: api/Movie
[HttpPost]
public IActionResult PostMovie([FromBody] MovieBundle Moviebundle)
{


if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var _movie = _context.Movies.FirstOrDefault(m => m.Code == Moviebundle.Movie.Code);
if(_movie == null)
{
//Doesn't exist! add a new one
_movie = Moviebundle.Movie;
_context.Movies.Add(_movie);
_context.SaveChanges();

foreach (Actor actor in Moviebundle.actors)
{
//Try to look up by name
Actor _actor = _context.Actors.FirstOrDefault(a => a.Name == actor.Name);

//If they don't exist, add them to the DB
if (_actor == null)
{
_context.Actors.Add(actor);
_context.SaveChanges();
_actor = actor;
}

//This is what I'm using to create the M-t-M relationship
var link = new MovieActor { Actor = _actor, Movie = _movie };
_context.MovieActor.Add(link); //This line gives an error


}


} else
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}




try
{
_context.SaveChanges();
}
catch (DbUpdateException)
{
if (MovieExists(_movie.MovieID))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}

return CreatedAtAction("GetMovie", new { id = _movie.MovieID }, _movie);
}

最佳答案

您必须如下所示更改它。

模型:

namespace Test.Models
{
public class Movie
{
public int MovieId { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Code { get; set; }
public string Path { get; set; }

public ICollection<MovieActor> MovieActors { get; set; }
}

public class Actor
{
public int ActorId { get; set; }
public string Name { get; set; }
public ICollection<MovieActor> MovieActors { get; set; }
}

public class MovieActor
{
public int MovieId { get; set; }
public Movie Movie { get; set; }

public int ActorId { get; set; }
public Actor Actor { get; set; }
}
}

上下文:

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

builder.Entity<MovieActor>().HasKey(x => new { x.MovieId, x.ActorId});

builder.Entity<MovieActor>()
.HasOne(m => m.Movie)
.WithMany(ma => ma.MovieActors)
.HasForeignKey(m => m.MovieId);

builder.Entity<MovieActor>()
.HasOne(m => m.Actor)
.WithMany(ma => ma.MovieActors)
.HasForeignKey(a => a.ActorId);

}

public DbSet<Movie> Movies { get; set; }

public DbSet<Actor> Actors { get; set; }

public DbSet<MovieActor> MovieActors { get; set; }

}

您可以导航,如下所示:

var actor = context.Actors
.Include(r => r.MovieActors)
.FirstOrDefault(a=>a.ActorId = 1)

var movies = actor.MovieActors.Select(c => c.Movie);

如何添加记录:

var actor = new Actor { ... };
context.Actors.Add(actor);

var movie = new Movie { ... };
context.Movies.Add(movie);

var movieActor = new MovieActor { Actor = actor , Movie = movie };
context.MovieActors.Add(movieActor);

context.SaveChanges();

关于entity-framework - Entity Framework 核心 : Include many-to-many related objects in WebAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39672601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com