Ir para conteúdo
Fórum Script Brasil
  • 0

EF4 - Problema ao adicionar novo registro


ursolouco

Pergunta

Salve,

Alguém poderia me explicar por qual motivo está disparando a exceção ao adicionar o registro na base?

Add.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PocoLibrary;

namespace ProjWebTestePoco
{
    public partial class Add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnAddCliente_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                try
                {
                    using (NorthwindPocoContext contexto = new NorthwindPocoContext())
                    {
                        Customer customer = new Customer();                        
                        customer.CustomerID = txtCodigoCliente.Text.Trim().Substring(0, 10);                        
                        customer.CompanyName = txtNomeEmpresa.Text.Trim().Substring(0, 80);
                        contexto.Customers.AddObject(customer);
                        contexto.SaveChanges();
                        lblMensagem.Text = "Cliente Registrado com sucesso";
                    }
                }
                catch (Exception ex)
                {
                    lblMensagem.Text = "<pre>" + ex.ToString() + "</pre>";
                }
            }
        }
    }
}
Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PocoLibrary
{
    public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
        public List<Order> Orders { get; set; }
    }
}
Add.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Add.aspx.cs" Inherits="ProjWebTestePoco.Add" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMensagem" runat="server" Text=""></asp:Label>    
            <table>
                <tbody>
                    <tr>
                        <td>Código do cliente:</td>
                        <td>
                            <asp:TextBox ID="txtCodigoCliente" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>Nome da empresa:</td>
                        <td>
                            <asp:TextBox ID="txtNomeEmpresa" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"> </td>
                    </tr>
                    <tr>
                        <td> </td>
                        <td>
                            <asp:Button ID="btnAddCliente" runat="server" onclick="btnAddCliente_Click" 
                                Text="Adicionar Cliente" />
                        </td>
                    </tr>
                </tbody>
            </table>
            <br />
            <a href="Default.aspx" target="_self">Listar Consumidores</a>
        </div>
    </form>
</body>
</html>
Exception
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
   at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
   at System.String.Substring(Int32 startIndex, Int32 length)
   at ProjWebTestePoco.Add.btnAddCliente_Click(Object sender, EventArgs e)

Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

Mesmo removendo o método substring() o problema permanece

System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Dados de cadeia ou binários seriam truncados.
A instrução foi finalizada.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   --- End of inner exception stack trace ---
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Objects.ObjectContext.SaveChanges()
   at ProjWebTestePoco.Add.btnAddCliente_Click(Object sender, EventArgs e)

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...