Created
February 12, 2015 15:03
-
-
Save AlexArchive/f0ccb790789669158416 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Microsoft.Data.Entity; | |
using Microsoft.Data.Entity.Metadata; | |
namespace ConsoleApp1 | |
{ | |
public class Program | |
{ | |
public void Main(string[] args) | |
{ | |
using (var context = new ApplicationContext()) | |
{ | |
//context.Users.Add(new User {UserName = "Admin"}); | |
//context.SaveChanges(); | |
var user = context.Users.Single(u => u.UserName == "Admin"); | |
user.Tweets.Add(new Tweet | |
{ | |
Text = "Hello, World.", | |
User = user | |
}); | |
context.SaveChanges(); | |
} | |
} | |
} | |
public class ApplicationContext : DbContext | |
{ | |
public DbSet<User> Users { get; set; } | |
protected override void OnConfiguring(DbContextOptions options) | |
{ | |
options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ConsoleApp1;Trusted_Connection=True;MultipleActiveResultSets=true"); | |
} | |
protected override void OnModelCreating(ModelBuilder builder) | |
{ | |
builder.Entity<User>().OneToMany(t => t.Tweets).ForeignKey(t => t.UserId); | |
} | |
} | |
public class Tweet | |
{ | |
public int Id { get; set; } | |
public int UserId { get; set; } | |
public User User { get; set; } | |
public string Text { get; set; } | |
} | |
public class User | |
{ | |
public int Id { get; set; } | |
public string UserName { get; set; } | |
public virtual ICollection<Tweet> Tweets { get; set; } = new List<Tweet>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment