Insertar en una base de datos con LINQ
Frecuentes
Visto 62 equipos
1
I'm having a problem with my database being detected. I recently added a database as you can see in the image below and my query looks right (the sql below it is what the linq is going to replace) but I'm not sure why Visual Studio is not detecting my database. When I try to add
using System.Data.Entities
I can't find it and I'm not using it already.
My current usings:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
The following screenshot may help you understand what I'm trying to say (open the image in a new tab to view it at 100% scale):
Gracias por su ayuda por adelantado!
2 Respuestas
3
Tienes algunos problemas:
You haven't added the model to your project. I don't see any ORM-related files in Solution Explorer for
SqlIntegrationWithVs
.Once you add the model, given that
BloodBank
no es propiedad deRegister
class; thus, it still won't exist in the current context.In general, ORMs put table-mapped classes in a separate namespace, for example
BloodBankDatabase.BloodBanks
, and objects which let you access table data are put in a specific class, so you'll end up with something like:using BloodBankDatabase; using (var context = new DatabaseContext(connectionString)) { var returnedPerson = from loginDetails in BloodBank where loginDetails.Username == usersInput select loginDetails.Username; }
Also, looking at your code, you don't seem to understand how C# work. For example:
No deberías llamar
cmd.Dispose()
dentro deusing (SqlCommand cmd = ...) { }
, porqueusing
ya hace eso.SqlDataReader
implementosIDisposable
, so you've forgotten theusing () { }
alrededor.You should't catch
Exception
.where Username == usersInput
doesn't make sense in this context; are you sure you understand lambda expressions?No
bool usernameTaken = false;
. Instead, declare the variable as close as possible to the location where you use it first.Validate your inputs before using them. What happens if
userInput
is empty? Or extremely long?
¿Cómo puedes mejorar?
Stack Oveflow is not a code review website. Once you get your code working (and only then), you may be interested in submitting it to https://codereview.stackexchange.com/
You may also be interested in reading a book to learn C#. C# in Depth by Jon Skeet is de facto THE book any C# beginner should read.
If you work in a company, insist in doing code reviews for every line of committed code. Try to get more experienced developers to review your code. If not, find someone (a friend, an old colleague) who is ready to review your code.
Análisis de código, available in paid versions of Visual Studio, will point out the issues like the forgotten
using () { }
blocks. This is much easier than checking on MSDN every class you use to see whether it's implementingIDisposable
.poliestilo is another tool which may interest you: it won't find errors per se, but will force you to use an uniform style across the code base.
Respondido 13 Abr '17, 13:04
@mainwa I should point out after reading your post fully in depth now I have a few responses to some things you said (no need to comment on the 100% correct things as they did help me). What do you mean by "SqlDataReader implements IDisposable, so you've forgotten the using () { } around it."? I was changing my exception earlier hence the unfinished catch. I am aware, I had the sql mentality in my head and since I couldn't see it was wrong I couldn't correct it. I declare the item I'm going to return at the start of the method for uniform-readability. usersInput is validated in the validation - user3653380
@user3653380: what I mean is that when you use any object which implements IDisposable
, Que debe: (except some very rare cases) embed it in a using (...) { ... }
. You already did it for SqlConnection
y SqlCommand
(but since you also dispose them manually, it will result in CA2202: No deseche los objetos varias veces warning), but it's missing for SqlDataReader
, que conducirá a CA2213: Los campos desechables deben desecharse. - Arseni Mourzenko
0
Intenta agregar
using System.Linq;
at the using statements.
contestado el 28 de mayo de 14 a las 14:05
I'm already using that. I'll add my using statements into the OP. Thanks for your suggestion though! - user3653380
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c# sql database or haz tu propia pregunta.
Debes agregar un
ORM
layer to your application likeEntity Framework
. - Hamlet HakobyanYes you have not added Entity Data Model in your project - Ehsan Sajjad
@HamletHakobyan Can you please elaborate on what an ORM layer is? I'm a novice unfortunately. Thanks for your response - user3653380
what is Bloodbank? because your query is misformed aswell. Try reading some documentation on the Entity Framework. - Complexity
@EhsanSajjad I'm pretty sure I did. This (prntscr.com/3nd5p9) is how I added it. Did I add it incorrectly? - user3653380