要求实现我的功能才能访问数据库

时间:2019-04-10 12:19:41

标签: database linq entity-framework-6

要求实现我的函数对数据库的访问权限,并且已执行某些操作。 如: 1)检查或阅读消息。 2)按日期检查并发布用户之间的所有通信。 3)查找所有用户的最新帖子。 但是,尽管本教程中有资料,但我仍无法弄清楚该怎么做。我能告诉你的。因此,我想请您看看我的代码,看看那里有什么,并帮助我。您不需要完全编写代码。就算您不费吹灰之力地冷静举几个例子,让我在LINQ和EntityFramework上编写这三个函数

我的代码:

   public bool CheckIfUnreadMessagesArePresent(int userId)
    {
        IList<MessageInfo> messageInfo = new List<MessageInfo>();
        MessageInfo messageIn = new MessageInfo();

        var sql = @"SELECT * FROM MessageInfo
        WHERE wasRead = 0 AND Id = @userId ORDER BY  date DESC";
        var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userId = messageIn.Id });
        return messageInfo.Any(messageIn.WasRead == true);

    }

    public IList<UserInfo> FetchMessagesFromConversation(int userID1, int userID2)
    {
        IList<UserInfo> messageInfo = new List<UserInfo>();
        MessageInfo messageIn = new MessageInfo();

        var sql = @"SELECT * FROM MessageInfo
        WHERE userID1 = 1 AND userID2 = 3 OR userID1 = 3 AND userID2 = 1 order by date DESC";
        var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId,userID2 = messageIn.ReceiverId});
        messageInfo.Insert(message);
        return messageInfo;
    }

    public IList<MessageInfo> FetchLastMessageFromEachConversation((int userID))
    {
        IList<UserInfo> messageInfo = new List<UserInfo>();
        MessageInfo messageIn = new MessageInfo();

        var sql = @"SELECT * FROM MessageInfo
        WHERE date IN (@SELECT max(date)
        FROM MessageInfo WHRERE date IN (
        SELECT max(date)
        FROM MessageInfo
        GROUP BY messageIn.ID, messageIn.ReceiverId
        ORDER BY date DESC, messageIn.ID, messageIn.ReceiverId) 
        GROUP BY if (messageIn.ID < messageIn.ReceiverId,
        concat(messageIn.ID, " - ", messageIn.ReceiverId), concat(messageIn.ReceiverId, " - ", messageIn.ID)))";
        var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId, userID2 = messageIn.ReceiverId });
        return messageInfo;
    }

我的数据库

    CREATE TABLE [dbo].[UserInfo](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Login] [varchar](50) NOT NULL,
[Password] [varchar](50) NOT NULL,
[FirstName] [nchar](10) NOT NULL,
[LastName] [nchar](10) NOT NULL,
[Email] [varchar](50) NOT NULL,
[RegistrationDate] [datetime] NOT NULL,
    )
    GO

    CREATE TABLE [dbo].[Messages](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[SenderId] [int] NOT NULL,
    [ReceiverId] [int] NOT NULL,
[Message] [varchar](500) NOT NULL,
[date] [datetime] NOT NULL,
[WasRead][bit] NOT NULL
    CONSTRAINT FK_UserInfoSender FOREIGN KEY (SenderId)
REFERENCES [UserInfo](Id),
    CONSTRAINT FK_UserInfoReceiver FOREIGN KEY (ReceiverId)
REFERENCES [UserInfo](Id)
    )
    GO

0 个答案:

没有答案