我正在使用 ASP.NET MVC C#,我發現了以下問題,我真的不知道我是否做對了,事實證明我在 API 專案中使用 Code First 創建了一個資料庫,但是現在我在使用 Entity Framework 創建模型的 Web 專案中使用相同的資料資料庫,我不想混合這兩個專案。在整個資料庫中有一個多對多相關的表,叫做CategoriaNegocios,這是Categoria和Negocio之間的關系,到目前為止還不錯,但是當從negocio保存categorias時,我得到一個錯誤,no finds the NegocioCategorias table,所以我的查詢是為什么要更改表的名稱?
我將留下 API 類 Negocio 中使用的代碼
public class Negocio
{
public Guid NegocioId { get; set; }
[Required]
public string RazonSocial { get; set; }
[Required]
public string NombreComercial { get; set; }
public virtual ICollection<Categoria> Categoria{ get; set; }
}
班級類別
public class Categoria
{
[Key]
public Guid CategoriaId { get; set; }
[Required]
public string Name{ get; set; }
public string Description { get; set; }
public virtual ICollection<Negocio> Negocio{ get; set; }
}
語境
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Negocio> Negocio{ get; set; }
public DbSet<Categoria> Categoria{ get; set; }
}
資料庫 在此處輸入影像描述
使用資料庫中的 EF 在 Web 中的代碼已經創建了 Class Business
public partial class Negocios
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Negocios()
{
this.Categorias = new HashSet<Categorias>();
}
[Key]
public System.Guid NegocioId { get; set; }
public string RazonSocial { get; set; }
public string NombreComercial { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Categorias> Categorias{ get; set; }
}
類類別
public partial class Categorias
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Categorias()
{
this.Negocios = new HashSet<Negocios>();
}
[Key]
public System.Guid CategoriaId { get; set; }
public string Nombre { get; set; }
public string Descripcion { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Negocios> Negocios { get; set; }
}
添加新 negocio 的代碼
var cates = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(negocios.Categorias);
var categorias = await db.Categorias.Where(c => cates.Contains(c.CategoriaId.ToString())).ToListAsync();
negocio.Categorias = categorias;
direccion.Historial = Utils.Utilidad.Historial(direccion, "");
negocio.Direccions = direccion;
negocio.Historial = Utils.Utilidad.Historial(negocios, "");
db.Negocios.Add(negocio);
await db.SaveChangesAsync();
在 SaveChangesAsync() 它給出了錯誤
錯誤影像 在此處輸入影像描述
錯誤堆疊
[SqlException (0x80131904): El nombre de objeto 'dbo.NegociosCategorias' no es válido.] System.Data.SqlClient.SqlConnection.OnError(SqlException 例外,布爾 breakConnection,Action
1 wrapCloseInAction) 3331296 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) 334 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) 4289 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) 514 System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader(Boolean isInternal, Boolean forDescribeParameterEncryption) 237 System.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, String endMethod, Boolean isInternal) 890 System.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult) 288 System.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult) 177 System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar,Func2 endFunction, Action1 endAction,Task` 1 承諾,布爾要求同步) 59 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務任務) 62 System.Data.Entity.Core.Mapping.Update.Internal。 d__8.MoveNext() 2574 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Data.Entity.Core.Mapping.Update.Internal.d__39.MoveNext() 595
[UpdateException:更新條目時發生錯誤。有關詳細資訊,請參閱內部例外。] System.Data.Entity.Core.Mapping.Update.Internal.d__39.MoveNext() 956 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter。 HandleNonSuccessAndDebuggerNotification(任務任務) 62 System.Data.Entity.Core.Objects.d__156
1.MoveNext() 897 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 62 System.Data.Entity.Core.Objects.<SaveChangesToStoreAsync>d__154.MoveNext() 491 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 62 System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__61.MoveNext() 472 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務任務) 62 System.Data.Entity.Core.Objects.d__151.MoveNext() 716
[DbUpdateException:保存不為其關系公開外鍵屬性的物體時發生錯誤。EntityEntries 屬性將回傳 null,因為無法將單個物體標識為例外源。通過在物體型別中公開外鍵屬性,可以更輕松地在保存時處理例外。有關詳細資訊,請參閱 InnerException。] System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 62 System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() 32 EsteticaWeb.Controllers.<Create>d__4.MoveNext() in C:\Users\Carlos Vidal\source\repos\EsteticaWeb\EsteticaWeb\Controllers\NegociosController.cs:93 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 32 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 62 System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) 92 System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) 22 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) 42 System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() 80 System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() 396 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) 42 System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() 50 System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) 188 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) 38 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) 29 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) 73 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) 52 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) 39 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) 38 System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) 43 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) 73 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) 38 System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) 231 System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) 172
我希望你能幫助我,我已經堅持了很長時間。
uj5u.com熱心網友回復:
首先,你在復制代碼,不要這樣做,但這不是核心問題。
答案很明顯
您沒有名為“dbo.NegociosCategorias”的表
您已經使用名為“dbo.CategoriaNegocios”的 EF 代碼優先方法創建了一個多對多關系表,EF 將創建一個連接表,其中包含兩個物體的名稱并在末尾添加后綴 s。
您可以使用 Fluent API 更改此表的名稱:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Negocio>()
.HasMany<Categoria>(s => s.Categorias)
.WithMany(c => c.Negocios)
.Map(cs =>
{
cs.MapLeftKey("NegocioId");
cs.MapRightKey("CategoriaId");
cs.ToTable("NegociosCategorias");
});
}
這會將多對多表的名稱更改為“dbo.NegociosCategorias”。
這是一種方式,不更改表名的相反方式是正確命名(顯然),我不確定你最終如何得到一個名為“NegociosCategorias”的表,因為它應該是“CategoriaNegocios”。
我認為你應該真正改變你的專案的結構,一個域和一個 web,所有與資料庫相關的都應該保留在域專案中,并且 web 專案只是參考域專案,這樣你就不必復制類。
我的意思是擁有一個專案已經令人困惑:
public class Negocio {
...
public virtual ICollection<Categoria> Categoria{ get; set; }
...
}
和另一個專案:
public partial class Negocios {
....
public virtual ICollection<Categorias> Categorias { get; set; }
....
}
為什么它甚至是一個部分類,您期望從其他源檔案中獲得更多?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/507013.html
標籤:C# 网 。网 asp.net-mvc 实体框架
