1

I do have a question regarding EF and databases. I am upgrading my application from former Ado.net to EF but in my code major business logic has been written at the database level.

My question is whether I need to have shift that logic from the database level to code level if I want to use EF, or if I can go with the same database logic with EF.

For example, one of my requirements is:

#Procedure#
CREATE PROCEDURE Getemp123
    (@gender VARCHAR(40))
AS
BEGIN
    IF (@gender = 'Male')
        SELECT
            D.Name, E.FirstName, E.Salary  
        FROM
            Employees E 
        LEFT JOIN
            Departments D ON D.ID = E.DepartmentId 
        WHERE 
            Gender = @gender
    ELSE
        SELECT 
            D.ID, E.FirstName, E.LastName  
        FROM
            Employees E 
        LEFT JOIN
            Departments D ON D.ID = E.DepartmentId 
        WHERE 
            Gender = @gender
END

But when I am using EF, then it will create class for if() condition not for else requirement #

Class:

public partial class Getemp123_Result
{
        public string Name { get; set; }
        public string FirstName { get; set; }
        public Nullable<int> Salary { get; set; }
}
1
  • What are you gaining by converting to EF? Are you sure you need to convert everything? You can still use both methods together in an application. Commented Apr 28, 2019 at 15:25

1 Answer 1

1

Because your project is migrating from WinForm App with current existing database and stored procedure.

You should only select tables (do not select stored procedure) when generate EF Designer from database.

And you can define your ViewModel like

class YourType
{
        public int ID { get; set; }
        public string Name  { get; set; }
        public string FirstName  { get; set; }
        public string LastName { get; set; }
        public int? Salary { get; set; }
}

In your Business Logic you can handle logic like

SqlParameter param1 = new SqlParameter("@gender", "male");
var result = db.Database.SqlQuery<YourType>("exec Getemp123 @gender", param1);

Another way if you don't want to create YourType, you can use dynamic object.

var result = db.Database.SqlQuery<dynamic>("exec Getemp123 @gender", param1);

foreach(var item in result)
{
     var firstname = item.FirstName;
     //check property in dynamic before using
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your solution . definitely this will work for my requirement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.