ASP.NET 实体框架插入(如果不存在)

本文关键字:如果 如果不 不存在 插入 NET 实体 框架 ASP | 更新日期: 2023-09-27 18:32:33

嘿,伙计们和女孩们:)

我目前正在尝试实现一个 c#/asp.net 代码优先实体框架数据库应用程序(在 azure 上),该应用程序将保存电影列表。每次我向应用程序索要电影时,它都会执行以下操作:

  1. 查询数据库
  2. 如果在数据库中找不到,则查询 TMDB
  3. 添加到数据库(无重复项)
我有一个有效的

查询,我有一个有效的TMDB解析器,我可以向数据库添加东西。当我尝试在我的关系中没有重复项时,就会出现问题。

我的设置:

电影

public partial class Movies
    {
        public Movies() { this.Genres = new HashSet<Genres>(); /* [...] */ }
        [Key]
        public int Movie_ID { get; set; }
        // [...]
        public virtual ICollection<Genres> Genres { get; set; }
    }

流派

public partial class Genres
{
    public Genres() { }
    [Key]
    public int Genre_ID { get; set; }
    public string Genre_Name { get; set; }
}

数据库访问类

==>这是我的问题出现的地方<==

Movies daMov = new Movies();
// [...]
foreach ( string genre in movieGenres )
        {
            Genres daGenre = await dataBaseContext.Genres.Where(
                        m =>
                            m.Genre_Name == genre
                        ).FirstOrDefaultAsync( );       // query genre from db
            // doesn't exist - firstOrDefault() returns default
            if ( daGenre == null || object.Equals( daGenre, default( Genres ) ) )               
            {
                daGenre = new Genres(); // create new in db
                daGenre.Genre_Name = genre;
                daMov.Genres.Add( daGenre ); // works fine, just that it creates a new genre
            }
            else
            {
                // here i've been googling around for some time and found the following 
                // (all with the same error)
                //db.Genres.Attach( daGenre ); // don't create new??
                //daMov.Genres.Add( daGenre ); // should work?
                //db.Entry( daGenre ).State = EntityState.Modified; // no it doesn't
            }
        }
// [...]
db.Movies.Add( daMov );
await db.SaveChangesAsync(); // DBHelper.cs:line 140

这就是我的 ASP.NET WebAPI 抛出的(清理过的)错误消息:

ExceptionMessage: 
An error occurred while saving entities that do not expose foreign key properties for their relationships. 
The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. 
Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.,
ExceptionType: System.Data.Entity.Infrastructure.DbUpdateException,
StackTrace:    
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at dotNETproject1.WebAPI.App_Code.DBHelper.<queryIMDB>d__0.MoveNext() in App_Code'DBHelper.cs: line 140
InnerException: 
    ExceptionMessage: Store update, insert, or delete statement affected an unexpected number of rows (0). 
    Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.,
    ExceptionType: System.Data.Entity.Core.OptimisticConcurrencyException,

ASP.NET 实体框架插入(如果不存在)

首先,

您需要将public virtual ICollection<Movies> Movies{ get; set; }添加到流派类中,以确保多对多关系。

编辑

我也看到你既有db也有dataBaseContext,这是错误的。您必须使用相同的数据库上下文

我认为这样的事情应该有效:

Movies daMov = new Movies();
// [...]
foreach ( string genre in movieGenres )
        {
            Genres daGenre = await db.Genres.FirstOrDefaultAsync(
                   m => m.Genre_Name == genre);
            // doesn't exist - firstOrDefault() returns default
            if ( daGenre == null || object.Equals(daGenre, default(Genres)))               
            {
                daGenre = new Genres(); // create new in db
                daGenre.Genre_Name = genre;
            }
            daMov.Genres.Add( daGenre );
            db.Movies.Add(daMov);
            await db.SaveChangesAsync();
        }