Моего кода:Неверного столбца, когда я не прошу для одного
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();
То, что я хочу сделать, это, у меня есть клиент таблицы и страна таблицы, теперь я хочу, чтобы показать клиент представление, где вместо того, чтобы показывать идентификатор страны, хранящейся на клиенте, я хочу показать название страны, мне сложно выполнить ее в 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, Действие1 wrapCloseInAction) +2418094
1 wrapCloseInAction) +5694468
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action
System.Data. SqlClient.TdsParser.ThrowExceptionAndWarning (TdsParserStateObject stateObj, булева callerHasConnectionLock, булева asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun (runBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader DATASTREAM, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, булева & dataReady) +3731
System.Data.SqlClien t.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader (SqlDataReader Д.С., RunBehavior runBehavior, String resetOptionsString) +379
системы .Data.SqlClient.SqlCommand.RunExecuteReaderTds (CommandBehavior cmdBehavior, runBehavior runBehavior, булева returnStream, булева асинхронные, Int32 тайм-аут, Задача & задачи, булева asyncWrite, SqlDataReader DS, булева describeParameterEncryptionRequest) +2064
System.Data.SqlClient.SqlCommand.RunExecuteReader (CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +375
1 c) +14
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
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func
3 операции, TInterceptionContext interceptionContext, Действие3 executing, Action
3 выполнены) +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 контекст, 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
1 операция) +190
System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +154
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable
1 forMergeOption) + 283 System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +15 System.Data.Entity.Internal.LazyEnumerator
1.MoveNext(): +45 System.Linq.Enumerable.SingleOrDefault (IEnumerable1 source) +121 System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable
1 последовательность) + 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(IQueryable
1 источник) +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, IDictionary
2 параметра) +157 System.Web.Mvc.C ontrollerActionInvoker.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.WrappedAsyncResult
2.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.WrappedAsyncResult
1.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.WrappedAsyncResult
1.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.WrappedAsyncVoid
1.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.WrappedAsyncVoid
1.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.WrappedAsyncVoid
1.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 шаг, булева & completedSynchronously) +155
В заголовке вы говорите о Linq2Sql, но вопрос, как представляется, о рамках сущности. Это слишком разные технологии.Вероятно, вы должны исправить свой титул. –
Начнем с вашей модели клиента. Он содержит список, поэтому у вас будет несколько стран для каждого клиента? Если вы не хотите удалить часть списка. Затем, предполагая, что вы правильно настроили отношения, вы сможете получить то, что хотите, с помощью команды db.clientes.Include (c => c.Country) .SingleOfDefault (c => c.Id == id); –
Где вы используете 'cliente_id'? Здесь в кодах нет 'cliente_id'. –