简体   繁体   中英

How do I put business logic in my ADO.NET Entity Framework classes?

I'd like to use the ADO.NET Entity Framework for data access, extend its objects for my business logic, and bind those objects to controls in my UI.

As explained in the answers to another question , I cannot extend ADO.NET Entity Framework objects with partial classes and use my custom methods in LINQ queries.

ADO.NET Entity Framework partial class http://img221.imageshack.us/img221/7329/clientsq0.gif

I don't want methods showing up in the Intellisense that are going to create run-time errors! How should I architect my application to avoid this problem?

VB.NET LINQ with custom method http://img83.imageshack.us/img83/1580/iswashingtongn0.gif

Do I need a data access Client class and also a business logic Client class? It seems like that will get confusing.

You can architect your solution using (Plain Old C# Objects) POCO's and Managers.

That way you separate the business logic from the value objects.

To make it "look pretty", you can mark your methods with the (this) modifier on the parameters so you can then use those methods as extension methods.

An example could make this pretty clear:

Location Value Object:

public class Location
{
    public string City { get; set; }
    public string State { get; set; }
}

Location Manager:

public static class LocationManager
{
    public static bool IsWashington(this Location location)
    {
        return location.State == "WA";
    }
}

Now, the extension methods will show up differently than the standard properties/methods on the object.

The "IsWashington" method can be called 2 ways

Location location = new Location { State = "WA" };
LocationManager.IsWashington(location);

OR

Location location = new Location { State = "WA" };
location.IsWashington();

Now you have separation of your business logic and value objects, yet you still can have "pretty" method calls.

If you feel your fellow devs (or you :) ) will abuse the extension method part, then just don't use it.

I also use entity framework and tried first to extend the classed but I soon found that was not a good solution so I ended up making new classes (in a new class library) which I prefixed with a B. I did not extend the entity classes.

If I have a class named NewsPost the business class is named BNewsPost and all business logic connected to that class is collected here. For join the returning elements of used to place the logic.

Not a very exiting solution but it did the trick.

regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM