¿Cómo puedo actualizar un registro contra una identificación específica en LINQ to SQL?Actualizar usando LINQ to SQL
Respuesta
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
LINQ es una herramienta de consulta (Q = Consulta) - por lo que no hay manera de LINQ magia para actualizar sólo la hilera, excepto a través de la (orientado a objetos) de datos de contexto (en el caso de LINQ- to-SQL). Para actualizar los datos, es necesario buscarlo fuera, actualizar el registro, y presentar los cambios:
using(var ctx = new FooContext()) {
var obj = ctx.Bars.Single(x=>x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}
O escribir un SP que hace lo mismo en TSQL, y exponer el SP a través de la técnica de contexto:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
En ausencia de información más detallada:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
Eso no compilará; Donde (pred) devolverá un IQueryable
¡Uy! Mi error. Corregido – spender
Puede usar el Single (pred) en lugar de Where (pred) .FirstOrDefault() ... –
public bool UpdateCustomerIno(CustomerInfo toUpdate)
{
bool successfullySaved = false;
var db = new DataClasses1DataContext();
try
{
var dbCstInfo = db.CustomerInfos
.Where(w => w.CustomerID == toUpdate.CustomerID)
.SingleOrDefault();
if (dbCstInfo != null)
{
dbCstInfo.FirstName = toUpdate.FirstName;
dbCstInfo.LastName = toUpdate.LastName;
db.SubmitChanges();
successfullySaved = true;
}
}
catch {
successfullySaved = false;
}
return successfullySaved;
}
No es un problema aquí (dado que es un nuevo contexto de datos), pero hay un error en DataContext que lo hace más eficiente de usar (para búsquedas de identidad) SingleODefault (predicado) que Where (predicate) .SingleOrDefault(). También; si falla, ¿por qué no dejas que arroje una excepción? Ah, y es IDisposable. –
actualización
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.Single(p => p.ProductName == "Toy 1");
product.UnitPrice = 99;
product.UnitsInStock = 5;
db.SubmitChanges();
Insertar
Dim db As New NorthwindDataContext
' Create New category and Products
Dim category As New Category
category.CategoryName = "Scott's Toys"
Dim product1 As New Product
category.ProductName = "Toy 1"
Dim product2 As New Product
category.ProductName = "Toy 2"
he encontrado una solución hace una semana. Puede usar los comandos directos con "ExecuteCommand
":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
En la declaración ExecuteCommand
, puede enviar la consulta directamente, con el valor para el registro específico que desea actualizar.
valor = 0 -> 0 es el nuevo valor para el registro;
código = {0} -> es el campo donde enviará el valor del filtro;
Código -> es el nuevo valor para el campo;
Espero que esta referencia ayude.
¿Por qué usar ExecuteCommand para actualizar? Parece un poco extraño hacer eso cuando simplemente puede actualizar el objeto y llamar a SubmitChanges. – DazManCat
DataClassesDataContext dc = new DataClassesDataContext();
FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);
fd.FatherName=txtFatherName.Text;
fd.FatherMobile=txtMobile.Text;
fd.FatherOccupation=txtFatherOccu.Text;
fd.MotherName=txtMotherName.Text;
fd.MotherOccupation=txtMotherOccu.Text;
fd.Phone=txtPhoneNo.Text;
fd.Address=txtAddress.Text;
fd.GuardianName=txtGardianName.Text;
dc.SubmitChanges();
- 1. ¿Cómo actualizar con Linq-To-SQL?
- 2. Cómo regenerar (actualizar) LINQ to SQL DataContext?
- 3. Usando LINQ to SQL con Oracle
- 4. Obtenga Id usando LINQ to SQL
- 5. LINQ To SQL Paging
- 6. forma más eficiente para actualizar con LINQ to SQL
- 7. LINQ-to-SQL CompiledQuery.Compile() con Actualizar, Eliminar, Insertar?
- 8. Herramienta SQL to LINQ
- 9. LINQ to SQL Peculiarities
- 10. LINQ to SQL -
- 11. LINQ to SQL PredicateBuilder
- 12. Linq-to-SQL ToDictionary()
- 13. linq to sql update standard
- 14. LINQ to SQL ForeignKeyReferenceAlreadyHasValueException error
- 15. LINQ to SQL OrdenarPor thenby
- 16. ¿Por qué no puedo actualizar los datos en la base de datos usando LINQ to SQL?
- 17. Entity Framework vs Linq to Entities vs Linq to SQL
- 18. LINQ to Entities cómo actualizar un registro
- 19. ¿Está desaprobado LINQ to SQL?
- 20. LINQ to SQL valores predeterminados
- 21. LINQ to SQL Conversion Overflows
- 22. Linq to SQL create table
- 23. Error LINQ to SQL Designer
- 24. LINQ to SQL SOUNDEX - posible?
- 25. LINQ to SQL e inmutabilidad
- 26. LINQ to SQL para Oracle.ODP
- 27. Linq-to-SQL y sp_reset_connection
- 28. LINQ To SQL Dynamic Select
- 29. NHibernate vs LINQ to SQL
- 30. LINQ to SQL vs ADO.Net
@Mathieu - ¿Usted propone que adivine valores para las 200 propiedades? necesitan venir de algún lado ... –
Lo siento, tenía algo en mente que no se muestra aquí, mi mal. – Mathieu
excelente ejemplo de actualización. gracias amigo –