【问题标题】:Invalid column when i am not asking for the one当我不要求列时,列无效
【发布时间】:2015-09-25 20:11:53
【问题描述】:

我的代码是:

cliente.Country = new List<dic_paises>();

dic_paises C = ((from data in db.dic_paises where data.id == 61  select data).SingleOrDefault());

cliente.Country.Add(new dic_paises() { id = C.id, nome = C.nome });
return View();

我想要做的是,我有一个表客户端和一个表国家,现在我想在视图中显示客户端,而不是显示存储在客户端中的国家/地区 ID,而是显示国家/地区名称,我很难在 mvc 中完成它,因为我是 mvc 新手。尝试使用视图模型,但没有得到预期的结果。

public partial class cliente
{
    public int id { get; set; }

    [StringLength(1024)]
    public string nome { get; set; }

    [StringLength(1024)]
    public string apelido { get; set; }

    [StringLength(1024)]
    public string email { get; set; }

    public List<dic_paises> Country { get; set; }
}

这是客户模型,这里是国家模型:

public partial class dic_paises
{
    public int id { get; set; }

    [Required]
    [StringLength(1024)]
    public string nome { get; set; }
}

这就是我在控制器中所做的,在 youtube 上看到了一个视频 ...

cliente cliente = db.clientes.Find(id);

if (cliente == null)
{
    return HttpNotFound();
}

cliente.Country = new List<dic_paises>();

dic_paises C = ((from data in db.dic_paises where data.id == 61  select data).SingleOrDefault());

cliente.Country.Add(new dic_paises() { id = C.id, nome = C.nome });
return View();

请尽你所能...

这是错误...

[SqlException (0x80131904): 列名“cliente_id”无效。]
System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔型 breakConnection,Action1 wrapCloseInAction) +2418094
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
1 wrapCloseInAction) +5694468
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +379
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,Boolean async,Int32 超时,Task& 任务,Boolean asyncWrite,SqlDataReader ds,Boolean describeParameterEncryptionRequest)+2064
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String 方法, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +375
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext
1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 操作,TInterceptionContext 拦截上下文,Action3 executing, Action3 执行)+72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand 命令,DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior 行为)+166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior 行为)+12
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior 行为) +36

[EntityCommandExecutionException:执行命令定义时出错。有关详细信息,请参阅内部异常。]

System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,CommandBehavior 行为)+103
System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +758
System.Data.Entity.Core.Objects.c__DisplayClass7.b__6() +90
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +154
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
1 操作) +190
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) +283 System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +15 System.Data.Entity.Internal.LazyEnumerator1.MoveNext() +45 System.Linq.Enumerable.SingleOrDefault(IEnumerable1 source) +121 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable1 序列) +40 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable1 query, Expression queryRoot) +59 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +114 System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +116 System.Linq.Queryable.SingleOrDefault(IQueryable1 源)+211 WebApplication2.Controllers.clientesController.Details(Nullable1 id) in C:\Users\dani1\Documents\Visual Studio 2015\Projects\WebApplication2\WebApplication2\Controllers\clientesController.cs:56 lambda_method(Closure , ControllerBase , Object[] ) +107 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 参数) +157 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult 结果) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9723757 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

【问题讨论】:

  • 在您的标题中,您谈到了 Linq2Sql,但问题似乎与实体框架有关。这些技术太不同了。您可能应该更正您的标题。
  • 让我们从您的客户模型开始。它包含一个 List 所以你将为每个客户有多个国家?如果那不是您想要的,请删除 List 部分。然后,假设您正确配置了关系,您应该能够使用 db.clientes.Include(c => c.Country).SingleOfDefault(c => c.Id == id);
  • 你在哪里使用cliente_id?在代码中,没有cliente_id
  • 这就是我找不到的!?
  • 这个错误意味着你映射的类错误。它假定dic_paises 有一个外键cliente_idcliente 类与其主键id 连接)。您需要显式映射外键。

标签: c# entity-framework linq linq-to-entities


【解决方案1】:

情况就这样解决了……

我猜这就是他们所说的视图模型

public class ClienteCountry
    {
        public cliente cli { get; set; }

        public dic_paises country { get; set; }
    }

控制器代码 ...

cliente ccc = (from data in db.clientes where data.id == id select data).FirstOrDefault();
                dic_paises ppp = (from data in db.dic_paises where data.id == ccc.pais select data).FirstOrDefault();
                ClienteCountry cc = new ClienteCountry();
                cc.cli = ccc;
                cc.country = ppp;
                ViewBag.id = id;
                return View(cc);

其中 id 是通过视图传递的参数...

在我看来我把这个...

@model  WebApplication2.Models.ClienteCountry

然后我就可以像这样使用我的属性...

@Html.DisplayNameFor(model => model.cli.nome)
@Html.DisplayFor(model => model.cli.nome)

@Html.DisplayNameFor(model => model.cli.apelido)
@Html.DisplayFor(model => model.cli.apelido)

@Html.DisplayName("Country")
@Html.DisplayFor(model => model.country.nome)

无论如何感谢你们所有人,...

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多