I am trying to update a shopping cart in my application using a gridview and a SQLDataSource control, I'm trying to set the update command parameters so that I can send values to my SQL Stored proc, but it keeps throwing an exception saying that it can't convert from nvarchar to string.
Given the below code;
ProductsDataSource.UpdateParameters.Add("Description", row.Cells[2].Text);
it seems that this method will not accept anything other than a String as it's second argument, so how can I convert that to other values to pass into my parameters?
I have already tried something like this;
int productID = int.Parse(row.Cells[1].Text);
but since that second parameter HAS to have a string argument, I can't insert it into my DB (Complaining it can't implicitly convert to string!)
you can specify parameter type on markup..
<UpdateParameters >
<asp:Parameter Name="paramName" DbType="String" Type="String" />
and you can set value on code behind.
ProductsDataSource.UpdateParameters["paramName"].DefaultValue = "parameter value";
OR you can use overloads of Add method without markup definition.
SqlDataSource1.UpdateParameters.Add("paramName", DbType.String, "parameter value");
Rather than directly answer why your code isn't working, I thought I'd present an alternative. Even if you fix your error with SqlDataSource, I believe it's bad to continue using in the long run. Using SqlDataSource as a control on your webpage sprinkles database code in your UI layer. This is very messy and we try to avoid that with modern applications. SqlDataSource also encourages magic strings instead of using strongly typed model objects.
A better alternative is to completely ditch SqlDataSource and use ADO.NET directly (perhaps through some micro-ORM such as Dapper). We can also move this logic into its own class, and follow the repository pattern. That class is best placed in a separate class library that your application then references, then you can reuse the class from other applications. I personally often have a console application so that I can test bits of my repository without having to go through the website.
Rather than having your website rely directly on this repository class though, we often work through an interface. This keeps our website from needing to directly depend on how the database logic is implemented. Often this is coupled with Dependency Injection, but that's a bit too big a subject for this post. I highly recommend you check out this excellent video about Dependency Injection.
So, here's our interface:
public interface IProductRepository
{
Product GetProductById(int id);
void UpdateProduct(Product product);
List<Product> GetAllProducts();
}
Now for the actual implementation:
public class SqlServerProductRepository: IProductRepository
{
private readonly string _connectionString;
public ProductRepository(string connectionString)
{
_connectionString = connectionString;
}
public Product GetProductById(int id)
{
using(var connection = new SqlConnection(_connectionString))
{
//QuerySingle is an extension method from Dapper
return connection.QuerySingle<Product>("select Name, Description, Id from Products where Id = #Id", new {Id = id});
}
}
public void UpdateProduct(Product product)
{
using(var connection = new SqlConnection(_connectionString))
{
//Execute is an extension method from Dapper
connection.Execute("update Products set Name = #Name, Description = #Description where Id = #Id", product);
}
}
public List<Product> GetAllProducts()
{
using(var connection = new SqlConnection(_connectionString))
{
//Query is an extension method from Dapper
//You'd likely want to implement filters/paging etc in a real world app
return connection.Query<Product>("select Name, Description, Id from Products").AsList();
}
}
}
You'll need a model class if you don't have an existing one:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Now the code in your website becomes much simpler:
//you can remove the direct reference to SqlServerProductRepository
//via Dependency Injection, not shown here
IProductRepository productRepository = new SqlServerProductRepository(connectionString);
var product = productRepository.GetProductById(1);
product.Description = "Updated Description";
productRepository.UpdateProduct(product);
ProductsGridView.DataSource = productRepository.GetAllProducts();
ProductsGridView.DataBind();
There's other ways you could go about implementing your repository, such as having it batch changes until you call SaveChanges etc, but this is a basic implementation.
Another advantage of abstracting your database interaction behind an interface is that you can try out different implementations without needing to change your entire website. Want to try Entity Framework? Create a new EntityFrameworkProductRepository that implements IProductRepository. What if you want to switch databases entirely? SqlLite is free and lightweight and suitable for small apps. Create a new SqlLiteProductRepository.
Try
string productID = (string)(row.Cells[1].Text)
Related
I have this action method in MVC which retrieves data from table using a DbContext:
public ActionResult Index()
{
TwitterContext context = new TwitterContext();
List<TwitterUser> Users = context.User.ToList();
return View(Users);
}
It retrieves the values as expected:
But when I use the same code as a service, it retrieves nothing:
I am calling the service method from the client like this
public class TwitterController : Controller
{
// GET: Twitter
public ActionResult Index()
{
TwitterServiceReference.TwitterContractClient client = new TwitterServiceReference.TwitterContractClient("BasicHttpBinding_ITwitterContract");
List<TwitterServiceReference.TwitterUser> user = client.User().ToList();
return View(user);
}
}
I am using the same connection strings in both cases
<add name="TwitterContext"
connectionString="Integrated Security=true;initial Catalog=TwitterDatabase;server=MYNAME-PC\SQLEXPRESS"
providerName="System.Data.SqlClient"/>
I have all the data filled in the table:
Why is the data empty? How to solve this?
UPDATE:
After checking the SQL Server i see that a database is generated with the name
"TwitterService.TwitterContext , the database is autogenerated when i run the app, and the autogenerated tables data is empty, that is why i am getting empty data returned.
i think you forgot to copy your web.config connection string to that app.config.This might be the issue.
Edit:
i mean the project in which your DataContext class resides
The TwitterUser type you are using in MVC is in namespace Twitter.Models but the one you are using in WCF is in namespace TwitterServiceReference. Therefore, EF will treat them like different things. Your TwitterContext is also in different namespaces and as a consequence this is what is happening (from your comment):
I Just checked the SQL Server Management studio, i think the code created database named "TwitterService.TwitterContext" don't know how and with the same tables as DbContext class
And since it is a brand new database, it has no data and therefore in the WCF service you are not getting any records.
You can have different contexts and use the same database by specifying the same connection string as shown below:
public class TwitterContext : DbContext
{
public MovieDBContext()
: base("TwitterContext")
{
}
}
A Better Approach
Create a separate project and put all your DbContext related code in that project. Most people will refer to this as the Data Access Layer. Then use that project in both the MVC application and the WCF services. This way you will share the TwitterUser and other types in both, and possibly more, applications. You may use Repository Pattern to implement this layer.
But what if my MVC application needs additional info?
There will be cases where TwitterUser may not be sufficient for your MVC views and you may need additional properties. In that case, you can create a Model specifically for that view (some people call this view model but I stay away from that since that is a term used in MVVM and it is very different). The class can be designed like this:
public class TwitterUserModel
{
public TwitterUserModel(TwitterUser user)
{
this.TwitterUser = user;
}
public string AnotherPropertyNeededByView {get; set;}
public TwitterUser TwitterUser { get; set; }
}
Or you can use AutoMapper or similar mappers to map from TwitterUser to TwitterUserModel.
After some trials i got the success
i just added this code
public class TwitterContext : DbContext
{
//Added this Code with the connection string
public TwitterContext() : base(#"Integrated Security=true;server=MYNAME-PC\SQLEXPRESS;database=TwitterDatabase")
{
//Disable initializer
Database.SetInitializer<TwitterContext>(null);
}
public DbSet<TwitterUser> User { get; set; }
public DbSet<TwitterUserData> UserData { get; set; }
}
I first tried adding "TwitterContext" as base("TwitterContext") which is the name of my connection string and matches with my DbContext class name which did not work, so i directly added the connection string, the data is retrieved now and is preventing from generating new database.
Abstract view: I want to pass information from one layer to another (note: when there's a better title for this thread let me know).
I have a ViewModel which communications with my Views and my Service layer.
And I have a Service layer communication with my persistence layer.
Let's assume I have the following classes:
public class EmployeeViewModel()
{
// The following properties are binded to my View (bidirectional communication)
public Firstname ...
public Lastname ...
public Email ...
public void PerformingSearch()
{
...
EmployeeService.Search(...);
...
}
}
public class EmployeeService()
{
public List<Employee> Search(...)
{
// Searching in db
}
}
What is best practice to hand over the data from my ViewModel to my Service layer (e. g. for performing a search)?
I see a few options (ViewModel perspective):
EmployeeService.Search(Firstname, Lastname, Email);
EmployeeService.Search(employeeSearchModel); // In this case I would need another model. How should the model be instantiated?
EmployeeService.Search(this); // Convertion has to be done somewhere
Is there any design pattern for this problem? How is it called? What option is best? Did I miss anything?
Describing your problem space
Your particular example tells me that your current architecture contains a service layer that sort of acts as a proxy to your data access layer. Without more in-depth knowledge of your architecture I would suggest a possible solution to keep it simple as much as your environment allows.
Now let's try to pick a strategy to get a possible solution model.
Your user story sounds like: "a user submits information to obtain a list of employees".
Your current use-case simplified:
UI: submits some information that you need to serve;
VM: receives the search terms and passes it next to the service layer;
SL: sends the received data to Data Access Layer (and maybe updates the response values to VM properties);
DAL: looks up information in persistence store and returns the obtained values.
A refactored use-case example:
VM: invokes a query with the needed values encapsulated and set the properties to display in the UI.
Looks easier right?
Enter: Command Query Separation
In short CQS:
States that every method should either be a command that performs
an action, or a query that returns data to the caller, but not both.
In your particular case we need to focus on queries, where:
Queries: Return a result and do not change the observable state of the system (are free of side effects).
But how does this help you? Let's see.
A very good and detailed explanation of CQS query-side can be read fully at the "Meanwhile... on the query side of my architecture" blog post from Steven.
Query concept applied to your problem
Defining an interface for the query object
public interface IQuery<TResult> {}
The query handler definition:
public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
TResult Handle(TQuery query);
}
Now here is an implementation of your "search" query object. This is effectively the answer for your "how to pass information" question :
public class FindEmployeeBySearchTextQuery : IQuery<Employee>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
And last a query handler that you will pass in your query object:
public class FindEmployeeBySearchTextQueryHandler
: IQueryHandler<FindEmployeeBySearchTextQuery, List<Employee>>
{
private readonly IDbContext db;
public FindEmployeeBySearchTextQueryHandler(IDbContext db)
{
this.db = db;
}
public List<Employee> Handle(FindEmployeeBySearchTextQuery query)
{
return (
from employee in this.db.employees
where employee.FirstName.Contains(query.FirstName) ||
employee.LastName.Contains(query.LastName) ||
employee.Email == query.Email
select employee )
.ToList();
}
}
Note: this Handle() example implementation uses Entity Frameworks' IDbContext, you have got to rework/modify this according to your needs (ADO.NET, NHibernate, etc.).
And finally in your view model:
public class EmployeeViewModel()
{
private readonly IQueryHandler _queryHandler;
public EmployeeViewModel(IQueryHandler queryHandler)
{
_queryHandler = queryHandler;
}
public void PerformingSearch()
{
var query = new FindEmployeeBySearchTextQuery
{
FirstName = "John",
LastName = "Doe",
Email = "stack#has.been.over.flowed.com"
};
List<Employee> employees = _queryHandler.Handle(query);
// .. Do further processing of the obtained data
}
}
This example assumes that you are using Dependency Injection.
You get IQueryHandler implementation injected into your view models constructor and later work with the received implementation.
Using this approach your code becomes cleaner, more use-case driven and will have better isolation of responsibilities which you can easily test and decorate with further cross-cutting concerns.
I have a database setup using 'master/slave replication'. I have one master and (at least) one slave, possibly ℕ slaves. For simplicity from here on I'll talk about one master, one slave because determining which slave to use includes some business-logic not relevant to the actual problem at hand.
Here's a schematic of the setup (with ℕ slaves):
In the application (currently using Dapper) I have the following, simplified, code:
abstract class BaseRepo
{
private readonly string _readconn;
private readonly string _writeconn;
public BaseRepo(string readConnection, string writeConnection)
{
_readconn = readConnection; //Actually IEnumerable<string> for ℕ slaves
_writeconn = writeConnection;
}
private SqlConnection GetOpenConnection(string cnstring)
{
var c = new SqlConnection(cnstring);
c.Open();
return c;
}
public SqlConnection GetOpenReadConnection()
{
return this.GetOpenConnection(_readconn);
// Actually we use some business-logic to determine *which* of the slaves to use
}
public SqlConnection GetOpenWriteConnection()
{
return this.GetOpenConnection(_writeconn);
}
}
class CustomerRepo : BaseRepo
{
// ...ctor left out for brevity...
// "Read" functions use the "read" connection
public IEnumerable<Customer> ListCustomers()
{
using (var c = this.GetOpenReadConnection())
{
return c.Query<Customer>("select * from customers order by name");
}
}
// "Write" functions use the "write" connection
public void UpdateCustomer(Customer cust)
{
using (var c = this.GetOpenWriteConnection())
{
c.Execute("update customers set name = #name where id = #id", cust);
}
}
}
My question is; suppose I want to use Entity Framework ("code first", should that be relevant) instead of Dapper; how would I best go about achieving the same concept; inserts/updates/deletes are executed against the "master" database and selects are executed against a slave (or any of the slaves). Does EF support this scenario at all? What would I need to do to make this work?
Additional info: I already use 'read-only' and 'write-only' users at the SQL Server level as a 'last line of defence' to prevent any mistakes in the DAL. What I'm looking for is a method of limiting my DAL to avoid having to catch SQL Server exceptions because of 'not allowed' actions and having to go to the (incorrect) SQL server in the first place before finding out the desired action is not allowed. I could use the same approach as I do now; instantiate/use the correct DbContext in the method itself (listcustomers/updatecustomer in the above example). I get that. But that would mean I'd have to create a 'wrapper' function for each "CRUD" action on each "entity" which was kind of why I was moving from dapper to EF in the first place; simply expose a DBSet and have EF take care of the changetracking/SQL queries etc. and now, hopefully, also figure out which connectionstring to use for each action.
As proposed by others, create a read/write context by default and then create a readonly one inheriting from it.
Also be sure to implement in a partial class a constructor accepting another configuration if you wish too.
public partial class CustomerEntities : DbContext
{
protected CustomerEntities(string nameOrConnectionString):base(nameOrConnectionString)
{
}
}
public class ReadonlyCustomerEntities : CustomerEntities
{
public ReadonlyCustomerEntities ()
: base("name=ReadonlyCustomerEntities")
{
}
public override int SaveChanges()
{
// Throw if they try to call this
throw new InvalidOperationException("This context is read-only.");
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am a newber in design pattern.
Currently I am developing a system where I have a releation DB. What would be the best approach to CRUD from my DB?
My current code looks like the follow (C# code):
I defined a inteface with commons functions to all classes.
namespace Model
{
public interface ICommon
{
void insert();
void update();
void delete();
}
}
The Common class (abstract one) implements ICommon interface and few orders methods and attributes.
namespace Model
{
public abstract class Common : ICommon
{
public Guid RecId { set; get; }
public abstract void insert();
public abstract void update();
public abstract void delete();
public abstract List<Common> find();
/// <summary>
/// Insert or update the record
/// </summary>
public void save()
{
if (this.RecId == Guid.Empty)
{
this.insert();
}
else
{
this.update();
}
}
}
}
Then, the proper class (UserTable class for example) extends the Common class and implements the abstracts methods and others particulars attributes.
The way that I am doing my CRUD its from StoresProcedures and SqlParameter, SqlCommand and SqlConnection. Here it is a example:
class CustTableModel : Common
{
public string SerialNumber { set; get; }
public string ApplicationVersion { set; get; }
public string KernelVersion { set; get; }
public string Name { set; get; }
public bool Active { set; get; }
public override void insert()
{
List<SqlParameter> parameters = new List<SqlParameter>();
SqlParameter parameter;
// SerialNumber
parameter = new SqlParameter("#serialNumber", System.Data.SqlDbType.Int);
parameter.Value = this.SerialNumber;
parameters.Add(parameter);
// ApplicationVersion
parameter = new SqlParameter("#applicationVersion", System.Data.SqlDbType.Int);
parameter.Value = this.ApplicationVersion;
parameters.Add(parameter);
// KernelVersion
parameter = new SqlParameter("#kernelVersion", System.Data.SqlDbType.Int);
parameter.Value = this.KernelVersion;
parameters.Add(parameter);
// Name
parameter = new SqlParameter("#name", System.Data.SqlDbType.Int);
parameter.Value = this.Name;
parameters.Add(parameter);
// Active
parameter = new SqlParameter("#active", System.Data.SqlDbType.Bit);
parameter.Value = this.Active;
parameters.Add(parameter);
DBConn.execute("CUSTTABLE_INSERT", parameters); // The code of DBConn is below.
}
}
Just to a better understanding, here it is the DBConn class:
public class DBConn
{
protected SqlConnection sqlConnection;
protected string command { set; get; }
protected List<SqlParameter> parameters { set; get; }
protected void openConnection()
{
this.sqlConnection = new SqlConnection();
this.sqlConnection.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=JYL_SOAWS_DB;Integrated Security=True";
this.sqlConnection.Open();
}
protected void closeConnection()
{
if (this.sqlConnection.State == System.Data.ConnectionState.Open)
{
this.sqlConnection.Close();
}
}
/// <summary>
/// Executa o processo no banco.
/// </summary>
/// <returns>Quantidade de registros afetados.</returns>
protected SqlDataReader run()
{
SqlCommand command = new SqlCommand();
SqlDataReader ret;
this.openConnection();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = this.sqlConnection;
command.CommandText = this.command;
if (this.parameters != null)
{
foreach (SqlParameter parameter in this.parameters)
{
command.Parameters.Add(parameter);
}
}
ret = command.ExecuteReader();
this.closeConnection();
return ret;
}
/// <summary>
/// Interface da classe à outros objetos.
/// </summary>
/// <param name="commandName">Nome da store procedure a ser executada.</param>
/// <param name="parameters">A lista com os parâmetros e valores.</param>
/// <returns>Numero de registros afetados.</returns>
public static SqlDataReader execute(string commandName, List<SqlParameter> parameters = null)
{
DBConn conn = new DBConn();
conn.command = commandName;
conn.parameters = parameters;
return conn.run();
}
}
I am pretty sure that there is a better way.
Could anyone help me? Thanks is advance.
You have hit upon two subtly different patterns here.
The first is the repository pattern - a way of abstracting away your business logic from your data access
The second is the Active Record pattern, whereby an entity is responsible for maintaining its own state in a database.
I would recommend you stay away from ActiveRecord in C# (you may or may not know about the Inversion of Control pattern right now, but it is very useful and fairly incompatible with AR).
I would suggest you look at something like dapper.net if you are starting out (I still use it in my smaller projects). It is a Micro-ORM which takes lots of the boilerplate away from using a database, without being opinionated or difficult to learn (I use and like EntityFramework & NHibernate, but they aren't anywhere as easy to pick up for a beginner).
Along with this, I would create a repository (a class with Create(Foo entity), Read(Guid entityId), Update(Foo entity) & Delete(Guid entityId) methods).
As an aside, be careful when using Guids as a primary key, as they can cause an interesting situation: Since most Guid implementations (almost always) have a non-sequential layout, and data is physically ordered by primary key, such inserts with can cause a lot of disk IO as the database reorders data pages on disk to accommodate new data inserted at some arbitrary position within the table. A good strategy for Guid generation for use as a primary key is to use a Guid Comb generator
Good Luck!
This is the best pattern. I advise not using an ORM. especially EF.
public class MyModel
{
public string Id {get;set;}
//public valuetype PropertyA {get;set;} //other properties
}
public interface IMyModelRepository
{
List<MyModel> GetModels();
MyModel GetModelById(string id);
void AddMyModel(MyModel model);
//other ways you want to get models etc
}
public class MyModelRepositorySql : IMyModelRepository
{
public List<MyModel> GetModels()
{
//SqlConnection etc etc
while (SqlDataReader.Read())
{
results.Add(this.populateModel(dr));
}
return results;
}
protected MyModel populateModel(SqlDataReader dr)
{
//map fields to datareader
}
public MyModel GetModelById(string id)
{
//sql conn etc
this.populateModel(dr);
}
}
Here's my reasoning:
Using the repository pattern allows you to inject ways of persisting your data which doesn't require a database. This is essential for unit testing, but also you will find it very useful if you can inject a mock repository into your project for integration testing.
Although ORMs might seem easy at first and save you a lot of typing, they cause problems in the long run. You only need to search stack overflow for entity framework questions to see the kind of knots people get themselves tied in when they hit a query that runs in a sub optimal way.
In any large project you will run across a data fetch requirement which requires some optimized way of retrieving data, which will muck up your carefully designed object graph/injectable generic repository or clever cutting edge ORM.
POCO objects are good. Complex objects (objects which have other objects as properties) are a pain in the arse when you attempt to serialise them or recursively add to the databases, etc. Keep your underlying data models POCO and only group them together in services or viewmodels using LINQ.
Well done for using GUID ids btw! Don't listen to those fools who think they will never run out of ints! (store as varchar(50) and let the DBA sort the indexing out) the problem with any DB generated id is you have to be able to create objects without connecting to the database.
For performing CRUD operations I would recommend Repository pattern with Entity framework.
Entity Framework is an ORM provided by microsoft. It deals with database using set of POCO Classes (Entity) to perform insert/update/delete/create operations.
To Execute queries against these entities, Language Integrated Query (LINQ) will be used. LINQ uses similar syntax of SQL and it returns database results as collection of Entities.
Here is a sample
Repository pattern with EF
Cheers!
In this sample code (C# winForms app) there is a Employee class with SearchEmployee() method and a DataService class with GetByEmployeeID() method. When searching for a employee, SearchEmployee() method will call GetByEmployeeID() method to talk to database. I have minimized the dependency between Employee class and DataService class by using constructor injection. (in its simplest way with out using an Interface)
But there is a dependency between Form class and Employee class as I new employee object from From class.
Will that dependency be a problem or isn't?
If that dependency should be avoided, What is the simplest way to achieve this?
I prefer not to use a pattern like MVP as I'm not familiar with it.
Class Form
{
public Form()
{
InitializeComponents();
}
private void btnSave_Click(object sender, EventArgs e)
{
Employee newEmp = new Employee (new DataService()); //Making a dependency
newEmp = newEmp.SearchEmployee (txtEmployeeID.Text);
txtEmployeeName.Text = newEmp.EmployeeName;
txtEmployeeAddress.Text = newEmp.EmployeeAddress;
}
}
Class Employee
{
string EmployeeID { get; set; }
string EmployeeName { get; set; }
string EmployeeAddress { get; set; }
DataService _DS;
public Employee(DataService DS) //Constructor injection of dataservice object
{
this._DS = DS;
}
public Employee SearchEmployee (string employeeID)
{
this.EmployeeID =employeeID;
DataTable DT= _DS.GetByEmployeeID(EmployeeID);
this.EmployeeName = DT.Rows[0].ItemArray[1].ToString();
this.EmployeeAddress = DT.Rows[0].ItemArray[2].ToString();
return this; //Returning an employee object to the caller
}
}
//This class responsible for database transaction
class DataService
{
public DataTable GetByEmployeeID(string employeeID)
{
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand Cmd = new SqlCommand("SELECT..WHERE emp_id=#employeeID", newCon);
Cmd.Parameters.Add("#employeeID", SqlDbType.varChar).Value = employeeID;
newCon.Open();
SqlDataReader rdr = Cmd.ExecuteReader();
DataTable results = new DataTable();
results.Load(rdr);
return results;
}
}
}
Actually, a class representing an entity should contain information relevant to that entity.
Any method that belong to the management of the entity, like looking for a specific object, telling which ones contain a set of properties and the like should be in a different class.
To make my point clear:
You can have your "Employee" with only the 3 string properties and then an "EmployeeManager" which is responsible of searching for employees, containing a list with all employees, looking by id, etc.
That way, you objects will be only information carriers and you will brake the dependency between them.
In your case, it makes more sense to have the "SearchEmployee" method on the Data Service.
Will that dependency be a problem or isn't? - It's not a problem here until how you want to get things done.
If that dependency should be avoided..? - Yes. Your program is having only one unit of work which is GetByEmployeeID(string employeeID). Dependency Injection(DI) is supposed to use when an employee object will need some other objects like department(which becomes dependency of employee object & will be injected via constructor pattern). In your program, dependency works like a service so there is almost no possibility that it alters its behavior depending on the caller. Also DI simplifies testing/mocking objects, testing employee object will eliminate the need of testing it's dependencies i.e. department.
What is the simplest way to achieve this?. I prefer not to use a pattern like MVP as I'm not familiar with it. -
Well, simplest requires solid base/architecture, then after your program will be able to accomplish this task in quite a few lines of code. You can use ORM(object relational mapper) frameworks like Microsoft entity framework which simplifies domain/data/repository/unit-of-work part.