2011-08-02 5 views
1

私はEFでPOCOを使って遊んでいます。ジェネリックのインターフェイスはなく、簡単に入力することができます。 まず、3つの属性を持つPerson:Personという1つの.edmxファイルを作成しました。 Id、FirstName、LastNameの順に表示されます。ObjectContextでデータベースに接続しようとしましたが、失敗しました。

これで私はデータベースを生成し、いくつかのレコードを手動で追加しました。このデータベースは、「PocoTest」と呼ばれると私のapp.configの接続ビットがどのように見えるされています

<add name="PocoTestContainer" connectionString="metadata=res://*/PocoTest.csdl|res://*/PocoTest.ssdl|res://*/PocoTest.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SEBASTIAAN-PC\SQLEXPRESS;Initial Catalog=PocoTest;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> 

まず私はエンティティを作成しました:

public class Person 
{ 
    public int Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

は、今私はObjectContextに継承、コンテキストを作成しました:

public class PocoTestContext : ObjectContext 
{ 
    private IObjectSet<Person> persons; 

    public PocoTestContext() 
     : base("name=PocoTestContainer", "PocoTestContainer") 
    { 
     ContextOptions.LazyLoadingEnabled = true; 
     persons = CreateObjectSet<Person>();   
    } 

    public IObjectSet<Person> Persons 
    { 
     get 
     { 
      return persons; 
     } 
    } 
} 

ここには何も表示されません。次の事はリポジトリです:

public class PersonRepository 
{ 
    PocoTestContext context; 

    public PersonRepository() 
    { 
     context = new PocoTestContext(); 
    } 

    public Person GetById(int id) 
    { 
     return context.Persons.Where(p => p.Id == id).FirstOrDefault(); 
    } 

    public List<Person> GetAll() 
    { 
     List<Person> persons = null; 

     try 
     { 
      persons = context.Persons.ToList(); 
     } 
     catch(Exception e) 
     { 
      Console.WriteLine(e.InnerException); 
     } 
     return persons; 
    } 

    public void Add(Person entity) 
    { 
     context.Persons.AddObject(entity); 
    } 

    public void Save() 
    { 
     context.SaveChanges(); 
    } 
} 

今、このすべてはうまくコンパイルが、私はすべての結果が返され得ることはありませんから、データベースに接続できないようです。 PocoTestContextコンストラクタでconnectionstateをチェックすると、接続は確立されません。 今私は接続ストリングを使う方法が間違っていると思っています。私は生成されたリポジトリを使用した別のプロジェクトからこのアプローチを盗んだ。

ご協力いただければ幸いです!

答えて

1

私は解決策を思いつきました、edmxファイルは 'PersonSet'への参照を保持していましたが、これを手動で 'Person'に変更しました。今私は期待される結果を得る。

1

コンストラクタで接続が確立されていません。必要なときに確立され、必要がなくなると閉じます。

+0

いいえ、これは私の問題の説明を変えてしまいます。返されたレコードはありません。 だから私は他の何か、そしてその方向へのポインタが欠けているはずですか? – duress

関連する問題