Skip to content

Instantly share code, notes, and snippets.

@19WAS85
Created December 22, 2011 17:18
Show Gist options
  • Save 19WAS85/1511065 to your computer and use it in GitHub Desktop.
Save 19WAS85/1511065 to your computer and use it in GitHub Desktop.
Passo a passo básico do Entity Framework Code First.
// Alterar.
using (var dataContext = new DatabaseContext())
{
var artigo = dataContext.Artigos.Find(1);
artigo.Title = "EF";
dataContext.SaveChanges();
}
// Remover.
using (var dataContext = new DatabaseContext())
{
var artigo = dataContext.Artigos.Find(1);
dataContext.Artigos.Remove(artigo);
dataContext.SaveChanges();
}
<connectionStrings>
<add name="DatabaseContext" connectionString="[INSIRA_SUA_CONNECTION_STRING]" providerName="System.Data.SqlClient" />
</connectionStrings>
public class Artigo
{
public Artigo()
{
Tags = new List<Tag>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public Autor Autor { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Autor
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Title { get; set; }
}
using (var dataContext = new DatabaseContext())
{
var artigo = dataContext.Artigos.Find(1);
}
using (var dataContext = new DatabaseContext())
{
var artigo = dataContext.Artigos
.Include(a => a.Tags)
.First(a => a.Title.Contains("Entity"));
}
var autor = new Autor { Name = "Wagner Andrade" };
var artigo = new Artigo
{
Autor = autor,
Title = "Entity Framework",
Text = "Uma forma simples e limpa de acessar os dados relacionais."
};
artigo.Tags.Add(new Tag { Title = ".NET" });
artigo.Tags.Add(new Tag { Title = "Desenvolvimento" });
artigo.Tags.Add(new Tag { Title = "ADO.NET" });
artigo.Tags.Add(new Tag { Title = "Entity Framework" });
using (var dataContext = new DatabaseContext())
{
dataContext.Artigos.Add(artigo);
dataContext.SaveChanges();
}
using (var dataContext = new DatabaseContext())
{
dataContext.Database.Create();
}
public class DatabaseContext : DbContext
{
public DbSet<Artigo> Artigos { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<Autor> Autores { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment