Link to home
Start Free TrialLog in
Avatar of ulf-jzl
ulf-jzlFlag for Sweden

asked on

Repository pattern, ADO.Net Entity Framework: Update Method.

HI!

I'm using the "Repository Pattern" and I like to have a Update method.

Need some help to write one.

This is what I have now.
public interface IRepository<T>
        where T : class
    {
        IEnumerable<T> FindAll();
        IEnumerable<T> FindBy(Expression<Func<T, bool>> filter);

        T FindById(int id);
        T FindById(string id);

        bool Add(T entity);
        bool Update(T entity);
        bool Remove(T entity);
    }


public class FileSystemWatcherRepository : IRepository<FileSystemWatcher>
{
    public IEnumerable<FileSystemWatcher> FindAll()
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Return all
            return ctx.FileSystemWatcher.ToArray();
        }
    }

    public IEnumerable<FileSystemWatcher> FindBy(Expression<Func<FileSystemWatcher, bool>> filter)
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Return item according to predicate 
            return ctx.FileSystemWatcher.Where(filter);
        }
    }

    public FileSystemWatcher FindById(int id)
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Return item by Id
            return ctx.FileSystemWatcher.Where(d => d.FileSystemWatcherId == id).FirstOrDefault();
        }
    }

    public FileSystemWatcher FindById(string id)
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Return item by folder path id
            return ctx.FileSystemWatcher.Where(d => d.FolderPath == id).FirstOrDefault();
        }
    }

    public bool Add(FileSystemWatcher entity)
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Add object to entity
            ctx.FileSystemWatcher.AddObject(entity);

            // Commit
            ctx.SaveChanges();

            // All ok
            return true;
        }
    }

    public bool Update(FileSystemWatcher entity)
    {
        ???
    }

    public bool Remove(FileSystemWatcher entity)
    {
        using (var ctx = new FbiDmsEntities())
        {
            // Delete object from entity
            ctx.FileSystemWatcher.DeleteObject(entity);

            // Commit
            ctx.SaveChanges();

            // All ok
            return true;
        }
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ulf-jzl

ASKER

thx man. :)

One question more, if you have the time. :)

I have a Store Procedure that executes the INSERT statement, I have done all the mapping and it works fine. The first insert works, but when I run it again it shold return affected rows  = zero.
But it always returns 1, even if the store procedure is empty.

If you have any thoughts about the code, please tell me, maybe I have done something strange. :)
[TestMethod]
public void AddTest()
{
    // Arrange
    IRepository<FileSystemWatcher> repository = new FileSystemWatcherRepository();

    FileSystemWatcher entity = new FileSystemWatcher() { FolderPath = @"C:\Test" };

    // Act
    bool actual = repository.Add(entity);

    // Assert
    Assert.IsTrue(actual);
}

public bool Add(FileSystemWatcher entity)
{
    // Get Entity
    using (var ctx = new FbiDmsEntities())
    {
        // Add object to entity
        ctx.AddToFileSystemWatcher(entity);

        // Commit
        int result = ctx.SaveChanges();

        // Affected rows
        if (result == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Use [FBI.DMS]; 
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
SET NOCOUNT ON;
GO	
-- ====================================================
-- Author:		
-- Create date: 2011-02-13
-- Description:	Insert a folder path
-- ====================================================
IF OBJECT_ID('InsertFileSystemWatcher') IS NOT NULL
	DROP PROC InsertFileSystemWatcher;
GO

CREATE PROCEDURE InsertFileSystemWatcher
(
	@FolderPath varchar(300)
)
AS
DECLARE @Id int;

BEGIN TRANSACTION FileSystemWatcherInsert
    WITH MARK N'Inserting a file system watcher folder path';
    
BEGIN
	-- Stops the message that shows the count of the number of rows affected
	SET NOCOUNT ON;
		
	-- Check so this folder path already exists
	SELECT @Id = [FileSystemWatcherId]
		 
	FROM dbo.[FileSystemWatcher]
	
	WHERE 
		[FolderPath] = 'C:\Test';		
END;

BEGIN
	--State 1: Do not insert if the folder path already exists, raise error
	IF 	@Id IS NULL
		BEGIN
			-- INSERT folder path	 	
			INSERT 
		         
			INTO dbo.[FileSystemWatcher]
			(
				[FolderPath]
			)
			VALUES
			(
				@FolderPath
			);			
		END;
	ELSE
		BEGIN
			RAISERROR ('The record already exists in the database.', 1, 1); 
		END;		
END;
	
-- commit the transaction
COMMIT TRANSACTION FileSystemWatcherInsert;
GO


-------------------------------------
Table
-------------------------------------
USE [FBI.DMS]
GO

/****** Object:  Table [dbo].[FileSystemWatcher]    Script Date: 02/17/2011 08:48:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[FileSystemWatcher](
	[FileSystemWatcherId] [int] IDENTITY(1,1) NOT NULL,
	[TimeStamp] [datetime] NOT NULL,
	[FolderPath] [nchar](300) NOT NULL,
 CONSTRAINT [PK_FileSystemWatcherSettings] PRIMARY KEY CLUSTERED 
(
	[FileSystemWatcherId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[FileSystemWatcher] ADD  CONSTRAINT [DF_FileSystemWatcherSettings_TimeStamp]  DEFAULT (getdate()) FOR [TimeStamp]
GO

Open in new window

This really should be a separate question with its own points assigned, but...

I'm not sure that I understand the comment that "the store procedure is empty." Stored procedures can't be empty, unless you mean the body of the stored procedure (i.e. it's an empty stored procedure that does nothing).

However, looking at the stored proc your problem would appear to be this line:

      WHERE
            [FolderPath] = 'C:\Test';

You're hard-coding the folderpath instead of comparing it to the one that's being passed in. So unless the first one you pass in is 'C:\Test' it will keep adding new ones. It should be:

      WHERE
            [FolderPath] = @FolderPath
Avatar of ulf-jzl

ASKER

I will move this to another question, so you can help me there instead.
Thx for the error, but what I mean is.

The ctx.SaveChanges();  always returns 1. even if I would empty the body of the store procedure.

The error I had did not solve the problem. it still return one even if it did not add any data to the table.