C#中的Oracle数据库和存储库模式

时间:2016-11-14 08:54:45

标签: c# oracle

我在oracle中创建了数据库。我通常使用以下代码连接到我的应用程序中的数据库:

OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
    sb.DataSource = "localhost";
    sb.UserID = "user";
    sb.Password = "password";
    OracleConnection conn = new OracleConnection(sb.ToString());
    conn.Open();

我也使用这段代码来做任何陈述:

OracleDataAdapter sd = new OracleDataAdapter("select, insert etc.", conn);

我们说我的数据库中有2个表,1个人,2个地方。现在我想为表创建存储库 - People。

那么,实现它的步骤是什么?如果我错了,请纠正我。

我创建了一个带有表属性的类:

    public class People
{        
    public int ID { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
}

然后,我创建了Interface:

    public interface IPeople
{
    void Insert(People person);
    void Update(People person);
    void Delete(People person);
    People GetById(People person);
    IEnumerable<People> SelectAll();
}

我不知道下一步是什么以及如何使用它。我很困惑,我在哪里连接到我的数据库? 对不起,也许我会问愚蠢而简单的问题,但是谷歌存储库模式,我仍然无法理解如何实现它并正确使用它。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

你可以像这样实现它,但这种方式不太好。我试着评论你要做的事情。正确使用类和名称的名称,如果您有问题,可以使用Resharper这是非常有用的工具。另外,其他写得更好的想法将使用一些ORM,如EntityFrameworkNHibernate

 //change class name and property names , You need to use coding conventions 
public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

//this is a person repository interface
public interface IPersonRepository
{
    void Insert(People person);
    void Update(People person);
    void Delete(People person);
    People GetById(People person);
    IEnumerable<People> SelectAll();
}

//this class implement your interface
class PersonRepository : IPersonRepository
{
    private OracleConnection conn;

    //add constructor which create connection to DB
    public PersonRepository()
    {
        OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
        sb.DataSource = "localhost";
        sb.UserID = "user";
        sb.Password = "password";
        conn = new OracleConnection(sb.ToString());
    }


    public void Delete(Person person)
    {
        throw new NotImplementedException();
    }

    public Person GetById(Person person)
    {
        //Use try finally block to open and close connection
        try
        {
            conn.Open();
            //example select by id
            OracleDataAdapter sd = new OracleDataAdapter("SELECT * FROM PERSON WHERE PERSON.Id == " + person.Id,
                conn);
            return new Person();
        }
        finally
        {
            conn.Dispose();
        }
    }

    public void Insert(Person person)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Person> SelectAll()
    {
        throw new NotImplementedException();
    }

    public void Update(Person person)
    {
        throw new NotImplementedException();
    }
}