Adding new methods to LINQ to SQL generated classes - asp.net

I am new to LINQ. I just dragged all my database tables onto the designer in a LINQ to SQL dbml. All my relationships are correct and look nice in the designer. I am able to pull data using simple LINQ code. I want to add my own methods now but don't want to blow away my changes if (when) I need to regenerate my dbml. I am guessing I just create a new class file and setup partial classes of the generated classes. Is this correct? For example, I have a generated class called SystemUser which contains the columns SystemUserId, Username, Password, PersonId, SecurityQuestionId, SecurityQuestionResponse. I want to add a method called void Authenticate() and a new property called bool Authenticated. Basically I want to pass in a username and password to Authenticate() and set the Authenticated property based on finding a matching user, etc. Where and how would I do this?

The LINQ-generated classes are partial classes, meaning you can extend them by creating your own partial classes or partial methods.
In your case, you can create a partial class for your SystemUser, and then add your method(s) in there. They will not be overwritten if the DBML file is regenerated.
Something like:
public partial class SystemUser
{
public bool Authenticated { get; set; }
void Authenticate()
{
//Perform custom logic here.
}
}

Take a look at using a Partial class... it might fit your situation very nicely.

If you just want your class to have a new method you are correct create a new file and use partial class.

Related

How to make changes in POCO file in Entity Framework so changes are retained

I am using Database First approach in Entity Framework. I have a table which contain one field called CustomerName and it is NOT NULL.
The generated POCO is given below.
public partial class Customers
{
public string CustomerName {get; set;}
}
I have two questions.
How can I make this a required field so my code would become like this (shown below). As you know POCO is automatically generated so after I do this and update model from database, all my code is removed.
public partial class Customers
{
[Required]
public string CustomerName {get; set;}
}
Second question is why EF automatically doesn't apply [Required] with this field when generating code? The field is NOT NULL in database so shouldn't this be done automatically without having to manually write [Required]?
Here's the answer if you're using EF6:
Notice that the generated Customers class is partial, we're going to leverage that. First, we'll need to create a new Customers partial class with the exact same name within the exact same namespace:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
public partial class Customers
{
}
}
Now both of these partials make up the same class it's just that the source code of this class is now split in different files, one of which is generated by the tool and one that you wrote by hand. The difference of course is that you can change the latter without it getting rewritten all the time.
Note that the namespace has to match but the folder that contains the class file doesn't.
Now we need to create the metadata class that contains all the necessary attributes and decorate our Customers partial with it, like so:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
[MetadataType(typeof(CustomersMetadata))] //decorating the entity with the metadata
public partial class Customers
{
}
public class CustomersMetadata //metadata class
{
[Required] //your data annotations
public string CustomerName { get; set; } //the property name has to match
}
}
and that's it.
Is it verbose? Yeah, but that decision was made when db first was chosen.
A word of caution:
If you're doing this to use entity classes as data models in MVC, generally speaking, that's considered a bad practice. The recommended way is to create separate model classes and map data from and to entities. There are some security reasons for that, which you should research before you make the final decision.
If you are using ef core then try adding --data-annotations flag in your scaffold command.
Please refer for more info: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding?tabs=dotnet-core-cli#fluent-api-or-data-annotations
EF doesn't have any means of validating your data in your POCO classes when it generates sql. That is why it is recommended that we should have a corresponding model object layer (corresponding model classes for your entities) that your application can manipulate. You can use something like AutoMapper for mapping between models and entities. In this way you can modify your model classes without impacting your EF entities.

Using code-first approach,I don't have an edmx file. what's the alternative?

I'm fairly new to asp.net mvc, so please bear with me.
I want to implement a calendar functionality, and all the tutorials I've looked at use database-first approach and have the edmx file (Entity Data Model)
I'm using code first and what can I do regarding the code that references this edmx file? do I reference context instead?
example:
public JsonResult GetEvents()
{
//Here MyDatabaseEntities is our entity datacontext (see Step 4)
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
var v = dc.Events.OrderBy(a => a.StartAt).ToList();
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Sorry if this question is vague or not clear.
Thank you and I'd appreciate help!
In code first, you don't need an edmx file, because everything is in your own code. The basic building blocks are:
A class that inherits from DbContext. This will be equivalent to the MyDatabaseEntities class in your sample.
A set of entity classes. They basically just need to be plain classes with auto properties corresponding to your database columns. For built in conventions to work, you also need an ID, for instance an int property named Id
A set of properties on your DbContext class of type DbSet for every type T which is an entity you would like to query against. This is the Events property in your example.
In more advanced scenarios you customize the mappings beyond what the conventions can infer automatically. This can be done with attributes on your entity classes, or via a special set of APIs that can be called on your context at startup
Go to Sql server inside your database there is a folder Database Diagram, Right click New Database Diagram and explore it.

Clarity about helpers in MVC3?

Are helpers in MVC3 used in the controller as well as the views?
Is a helper the right place to put commonly used controller methods?
I want to create a common method to get all sub children IDs in a database and make sure it is in the right area. I just want to make sure I am putting my logic in the right area.
Thanks
You could implement a base Controller for that logic. Helpers, or extension methods, are good for when you don't want to change the interface for something.
The HtmlHelper is not available to the controller, because the controller should not be responsible for generating HTML, but the UrlHelper is available within the controller.
A method to get specific data from your database does not belong in your controller, or in a UrlHelper or an HtmlHelper. You should create a separate class for this logic, and then call the method on this class from within your controller. If you are using Dependency Injection, which I suggest, your controller code might look like this:
public class MyController
{
IMyDataUtil _dataUtil;
public MyController(IMyDataUtil dataUtil)
{
_dataUtil = dataUtil;
}
public ActionResult SomeAction(int parentId)
{
var childIds = _dataUtil.GetChildIds(parentId);
...
}
}
As you can see, this allows you to keep the data-access code in a class specifically designed for that purpose. The fact that this controller depends on that utility class is immediately obvious, and doesn't take that much more code than calling an extension method on a helper. Controllers that don't deal with that class's methods won't need to have it available.
On the other hand, if there are methods that are likely to be used by a bunch of different controllers, injecting this same data class into all of them may become cumbersome. In that case, you could:
Extend a base class that has an instance of the data-access class injected into it via method or property injection, and which then exposes it to sub-classes via a protected or public property, or
Create your own helper class that wraps the classes and methods you're likely to use in all your controllers, and inject that class so you only have one dependency for a variety of common functions, or
Combine steps 1 and 2.
If by "helpers" you're referring to things such as HtmlHelper then, no, these aren't used by the controller as in theory you could take your controllers and re-use them with an entirely different rendering engine (for example WPF) as the controller isn't responsible for rendering.
If you're talking about, as I think you are, helper classes/methods that manipulate your data ready for it to be put into a Model by a Controller and then handed off to a View for presentation, then you could consider a "business logic" layer. For example, if you were talking about (the ever typical) Bank Account example, you could have a:
public class BankAccountService
{
public IEnumerable<string> GetAllAccountIdsForCustomer(int customerId)
{
// Talk to the database here and retrieve the account id's for a customer
}
public string GetCustomerName(int customerId)
{
// Talk to the database here and retrieve the customer's name
}
}
Your controller would then:
public ActionResult AccountNumbers(int customerId)
{
var model = new AccountNumbersModel();
model.CustomerId = customerId;
model.AccountNumbers = BankAccountService.GetAllAccountIdsForCustomer(customerId);
return View(model);
}
Obviously in this example you'd need to have a class called AccountNumbersModel defined and you'd also probably want to consider using Dependency Injection to provide an instance of BankAccountService to your controller, but describing how to go about all that is kinda outside the scope of this answer.
The advantages this approach gives you are testability and separation, each piece of code is responsible for one task, and you reduce the complexity of each individual piece and make it easier to make changes without breaking things.
I want to create a common method to get all sub children IDs in a database and make sure it is in the right area. I just want to make sure I am putting my logic in the right area.
That sounds like a job for an ActionFilter.

Initiate Properties automatically using StructureMap

If i have N numbers of classes on each of them i am declaring for example property which contains some app setting values from config file.
public static IAppSettings AppSettings { get; set; }
I want to populate this property automatically when class is created.
I am thinking to achieve this goal using StructureMap.
I want to "say" somehow only in one place, that if class contain this property populate it.
May be some one came across this and have any ideas?
ASP.NET/ASP.NET MVC, ConsoleApp/WinForms
If i have N numbers of classes on each
of them i am declaring for example
property which contains some app
setting values from config file.
You should consider having those N classes derive from a base class which contains this property:
public abstract Base
{
public IAppSettings AppSettings { get; set; }
}
then if you want to have this property automatically populated by StructureMap you should no longer instantiate them manually but always ask the container for a value.
For example in a ASP.NET MVC application I would use constructor injection to pass the value of IAppSettings to all the controllers that need it.
It sounds like you want a variation of the SettingsScanner described in this post: http://lostechies.com/joshuaflanagan/2009/07/13/how-we-handle-application-configuration/
You can get the full code for the scanner and ISettingsProvider from The FubuMVC source code:
https://github.com/DarthFubuMVC/fubumvc/blob/2e7ea30391eac0053300ec0f6f63136503b16cca/src/FubuMVC.StructureMap/SettingsScanner.cs

Remove field in wsdl in Asp.net webservice

I'm generating dto classes with a template engine and would like to exclude some properties in an asmx webservice, what, if possible, is the best way to do this?
Ex:
[WebMethod]
public ProductPackages GetPackages()
{
ProductPackages packages = new ProductPackages();
packages.Packages.add(new PackageDTO());
return packages;
}
The PackageDTO contains some properties that's not relevant for this service.
But as the class can be regenerated any time i can't apply [XmlIgnore] to the fields.
So I'm looking for a way to apply a "exclude list" without touching the actual class.
Above is just an example, the template engine generates dto's for all tables in a given project, and I would like to be able to use them in services without needing to maintain a big bunch of nearly identical classes.
Just hit the same problem. You can exclude fields by marking them as internal.
public class Order
{
public double OrderPrice;
internal double ProfitMargin;
internal string TheTruthAboutThisCustomer;
}
If you don't want to return a field or property, then don't have it in the object you return! It's as simple as that.

Resources