Skip to content

Instantly share code, notes, and snippets.

@robsonfaxas
Created June 11, 2021 02:21
Show Gist options
  • Save robsonfaxas/f39ff02c81505699c9a0a1cce6b732b6 to your computer and use it in GitHub Desktop.
Save robsonfaxas/f39ff02c81505699c9a0a1cce6b732b6 to your computer and use it in GitHub Desktop.
[LinqToSql - Mapeamento de tabela por código] Mapeamento de tabela por código #linq
No linqToSql você tem esses passos:
/* ############################################################################ */
1 - Cria-se uma entidade (ProductCategory, por exemplo)
* Aponta ela como sendo a tabela por data notation;
* Aponta suas propriedades como sendo Colunas por data notation;
* Informa a propriedade que IsPrimaryKey
/* ############################################################################ */
using System.Data.Linq.Mapping;
namespace LinqSql
{
[Table(Name = "Production.ProductCategory")]
class ProductCategory
{
[Column]
public int ProductCategoryID { get; set; }
[Column]
public string Name { get; set; }
[Column(Name="rowguid")]
public Guid guid { get; set; }
[Column]
public DateTime ModifiedDate { get; set; }
}
}
/* ############################################################################ */
2 - Cria-se um objeto que herda DataContext (AdventureWorks, por exemplo) e que conterá o Get da entidade. "DataContext" controla a comunicação entre LINQ e a fonte de dados. Então por ela é informada a existência de ProductCategory no LINQ.
* O construtor deve repassar para o base() a connectionstring
/* ############################################################################ */
using System.Data.Linq;
namespace LinqSql
{
class AdventureWorks : DataContext
{
public AdventureWorks(string connection) : base(connection) { }
public Table<ProductCategory> ProductCategories
{
get { return this.GetTable<ProductCategory>(); }
}
}
}
/* ############################################################################ */
3 - Consumir através de instância da classe AdventureWorks, utilizando linq.
/* ############################################################################ */
class Program
{
static void Main(string[] args)
{
AdventureWorks dc = new AdventureWorks(@"Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI");
var result = from pc in dc.ProductCategories
orderby pc.Name select pc;
//Em sintaxe de método ficaria da seguinte forma:
//var result = dc.ProductCategories.OrderBy(pc => pc.Name);
foreach (var item in result)
{
Console.WriteLine(item.Name);
}
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment