Created
August 28, 2013 08:57
-
-
Save 0xorial/6363788 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.Collections.Generic; | |
using System.ComponentModel.DataAnnotations.Schema; | |
using System.Data.Common; | |
using System.Data.Entity; | |
using System.Linq; | |
using Npgsql; | |
namespace ConsoleApplication1 | |
{ | |
[Table("books", Schema = "public")] | |
public class book | |
{ | |
public int id { get; set; } | |
public string name { get; set; } | |
public int author_id { get; set; } | |
[ForeignKey("author_id")] | |
public virtual author Author { get; set; } | |
} | |
[Table("authors", Schema = "public")] | |
public class author | |
{ | |
public int id { get; set; } | |
public string name { get; set; } | |
public virtual ICollection<book> Books { get; set; } | |
} | |
class Program | |
{ | |
class c : DbContext | |
{ | |
public IDbSet<book> Books { get; set; } | |
public IDbSet<author> Authors { get; set; } | |
public c(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) | |
{ | |
} | |
} | |
static void Main(string[] args) | |
{ | |
var csb = new NpgsqlConnectionStringBuilder(); | |
csb.Host = "localhost"; | |
csb.Port = 5432; | |
csb.UserName = "postgres"; | |
csb.Password = "z"; | |
using (var c = new c(new NpgsqlConnection(csb.ConnectionString), true)) | |
{ | |
// both entities are no-tracking | |
var bookFromSet = c.Set<book>().SqlQuery("select * from books").AsNoTracking().First(); | |
var bookFromDatabase = c.Database.SqlQuery<book>("select * from books").First(); | |
// this is not null, as expected | |
var authorFromSet = bookFromSet.Author; | |
// this is strangely null, I cannot find this behavior documented... | |
var authorFromDatabase = bookFromDatabase.Author; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment