2010-02-25 7 views
7

Visual Studio, C#, SQL 2005 server. Estoy intentando hacer coincidir el tipo de datos de la tabla .dbml con mi archivo .cs. El objetivo es permitir que una imagen se cargue en la base de datos. Hasta ahora no está funcionando. El problema parece estar relacionado con el tipo de archivo para la columna de la fileContent. he intentado varias variaciones diferentes, pero ninguno ha funcionado.¿Qué tipo de datos usar para esto para que la imagen pueda cargarse en el servidor SQL?

<Column Name="FileName" Type="System.String" DbType="NVarChar(100)" CanBeNull="true" /> 
<Column Name="FileType" Type="System.String" DbType="NVarChar(100)" CanBeNull="true" /> 
<Column Name="FileSize" Type="System.int32" DbType="int" CanBeNull="true" /> 
<Column Name="FileContent" Type="System.Data.Linq.Binary" DbType="varbinary(MAX)" CanBeNull="true" /> 

columnas de SQL Server
Applicant_PK (PK, int, notnull)
nombre de archivo (nvarchar (100), null)
FileType (nvarchar (100), nulo)
FileSize (int, null)
FileContent (varbinary (max), nula)

void CreatePreApplication() 
{ 
    Pre_Application = new PreApplication(); 
    Pre_Application.FileName = Path.GetFileName(ctrFile.PostedFile.FileName); 
    Pre_Application.FileType = ctrFile.PostedFile.ContentType; 
    Pre_Application.FileSize = ctrFile.PostedFile.ContentLength; 
    byte[] fileContent = new byte[ctrFile.PostedFile.ContentLength]; 
    ctrFile.PostedFile.InputStream.Read(fileContent, 0, ctrFile.PostedFile.ContentLength); 
    Pre_Application.FileContent = fileContent;  

public class PreApplication 

{public int DatabaseID {get; conjunto; } public String FileName {get; conjunto; } public String FileType {get; conjunto; } public int FileSize {get; conjunto; } byte público [] FileContent {get; conjunto; } PRESOLICITUD pública()

{ 
    PreApplicationsDataContext db = 
     new PreApplicationsDataContext(
      "Data Source=THESQLSERVER;Initial Catalog=THECONNECTIONSTRING;Integrated Security=True"); 
    tblPreApplication preApp = new tblPreApplication(); 
    preApp.FileName = FileName; 
    preApp.FileType = FileType; 
    preApp.FileSize = FileSize; 
    preApp.FileContent = (byte[])FileContent; 
    try 

    { 
     db.tblPreApplications.InsertOnSubmit(preApp); 
     db.SubmitChanges(); 
     DatabaseId = preApp.Applicant_PK; 
     return preApp.Applicant_PK; 
    } 
    catch 
    { 
     DatabaseId = 0; 
     return 0; 
    }   
} 

Gracias por mirar esto. Soy un novato en programación, así que si me haces una pregunta, por favor ten esto en cuenta.

+0

¿Puede decirnos qué error está recibiendo o qué síntomas son? –

+0

Probé el Type = "System.Byte []" y DbType = "image" y las NullRefferenceExceptions recibidas no fueron manejadas por el código de usuario.
Referencia de objeto no establecida en una istancia de un objeto.
Utilice la palabra clave "nueva" para crear una instancia de objeto. Verifique para determinar si el objeto es nulo antes de llamar al método. – Javier

Respuesta

1

Veo el problema ... está creando la conexión db y tratando de insertarla en el constructor.

su debe ser de clase se define como tal

public PreApplication() { 
} 

public DoInsert { 
    PreApplicationsDataContext db = 
    new PreApplicationsDataContext("Data Source=THESQLSERVER;Initial Catalog=THECONNECTIONSTRING;Integrated Security=True"); 
    tblPreApplication preApp = new tblPreApplication(); 
    preApp.FileName = FileName; 
    preApp.FileType = FileType; 
    preApp.FileSize = FileSize; 
    preApp.FileContent = (byte[])FileContent; 
    try { 
    db.tblPreApplications.InsertOnSubmit(preApp); 
    db.SubmitChanges(); 
    DatabaseId = preApp.Applicant_PK; 
    return preApp.Applicant_PK; 
    } catch { 
    DatabaseId = 0; 
    return 0; 
    } 
} 

y entonces su función de ejecutar

void CreatePreApplication() { 
    Pre_Application p = new PreApplication(); 
    p.FileName = Path.GetFileName(ctrFile.PostedFile.FileName); 
    p.FileType = ctrFile.PostedFile.ContentType; 
    p.FileSize = ctrFile.PostedFile.ContentLength; 
    byte[] fileContent = new byte[ctrFile.PostedFile.ContentLength]; 
    ctrFile.PostedFile.InputStream.Read(fileContent, 0, ctrFile.PostedFile.ContentLength); 
    p.FileContent = fileContent; 

    //do the insert after you have assigned all the variables 
    p.DoInsert(); 
} 
0

me vuelva a comprobar la cadena de conexión, si está trabajando localmente usar "" para THESQLSERVER, y asegúrese de que el catálogo inicial = NameOfDataBase. Si no está seguro de qué objeto es nulo, intente recorrerlo en el depurador y sitúe el cursor sobre la variable db. Asegúrate de que no sea nulo.

También puede ser útil tener una captura de prueba para manejar mejor cuando las cosas van mal. Por lo que es posible que desee leer sobre el manejo de excepciones.

Por último, no es una mala idea para asegurarse de que el vapor de agua se encuentra al principio antes de leer o siempre se puede restablecer como tal:

// Ensure stream is at 0 index. 
if (stream.Position != 0) 
{ 
    stream.Seek(0, SeekOrigin.Begin); 
} 

Espero que ayude un poco,

Eddy

Cuestiones relacionadas