如何创建使用各种不同数据库实现的c#接口

时间:2013-05-30 07:44:54

标签: c# mongodb interface object-model

我正在设计一个在Web应用程序中使用的对象模型。

该模型包含用户。每个用户都有会话。每个会话都包含该会话的记录和事件。我需要做的是保留数据(看起来像mongodb,或类似)我如何将此代码作为API保存到我的数据库,API的使用者将不需要知道它是如何存储的。它将“神奇地”起作用。

谢谢!

这是我现在使用的设计。

public class User
    {
        public int id {get; set;}
        public DateTime EnrollDate { get; set; }
        public string Udid { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public HashSet<Session> Sessions { get; set; }
        public HashSet<Session> GetSessions()
        {
            if (Sessions == null)
            {
                Sessions = new HashSet<Session>();
            }
            return Sessions;
        } 
    }

public class Session
    {
        public string SessionId { get; set; }
        public DateTime Time { get; set; }
        public JObject Parameters { get; set; }
        private List<Event> Events { get; set; } 
        private List<Record> Records { get; set; }
        public List<Event> GetEvents()
        {
            if (Events == null)
            {
                Events = new List<Event>();
            }
            return Events;
        }
        public List<Record> GetRecords()
        {
            if (Records == null)
            {
                Records = new List<Record>();
            }
            return Records;
        }
    }
 public class Record
    {
        public Record()
        {
            RecordId = Guid.NewGuid().ToString();
            CreatedAt = DateTime.Now;
        }
        public string Name { get; set; }
        public string RecordId { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime Time { get; set; }
        public JObject Data { get; set; }
    }

 public class Event
    {
        public Event()
        {
            EventId = Guid.NewGuid().ToString();
            CreatedAt = DateTime.Now;
        }
        public string EventId { get; set; }
        public string Name { get; set; }
        public DateTime Time { get; set; }
        private DateTime CreatedAt { get; set; }
        public JObject Parameters { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

我建议您阅读存储库模式。它允许您编写代码,而无需预先考虑数据访问的具体实现。

我会将这些接口构建到自己的程序集以及一个存储库接口,该接口定义使用您在上面定义的接口从数据存储中检索数据的合同。

您的应用程序将纯粹使用接口定义进行数据访问,您可以使用Unity等注入存储库和数据对象的具体实现。

此外,这将有助于对代码进行单元测试,因为您可以注入测试业务对象的测试存储库,例如

有关示例,请参阅here