开发者

Passing LINQ var to base add method C#

I am creating a DAL layer for my webpage and i am using LINQ for the first time.

at the moment I have a class called CargoTypeCollection which runs a query like:

   AHDBDataContext db = new AHDBDataContext();

   var CargoTypes = from cargoTypes in db.cargoTypes
                         select cargoTypes;

Now I want to pass the CargoTypes variable to my base add class (which just CargoTypeCollections inherits from)

reason for this is so I can have different methods do differnet things but I dont need to repea开发者_如何学Ct code. Base add class looks something like:

protected void baseAdd(var CargoTypes)
{
   foreach (var cargo in CargoTypes)
     {
       CargoTypeEntity cargo = new CargoTypeEntity();
       cargo.CargoTypeID = cargo.CargoTypeId;
       cargo.CargoName = cargo.CargoName;
       CargoTypes.Add(Cargo)
      }
}

(dont mind the few typoes i didnt cut and paste)

But obviously this doesnt work because I cant use var in method signature.


You can try using generic repository. Generics will solve the problem where you want to reuse same logic across multiple types. Repository, on the other hand, is a good way to provide an extra extraction to your DAL. By combining generics with repository, you achieve a DAL that is reusable across multiple types without having to write similar code for each types.

Repository is a deep topic though, not to say using it with generics. So I would suggest you looking for a few reference article to get started. For example, you might want to read this article to have a feel of what generic repository is like.


Try this:

protected void baseAdd(IQueryable<CargoType> cargoTypes)

The code below will set CargoTypes to IQueryable<T>, where T is the type of your 'db.cargoTypes' elements.

var CargoTypes = from cargoTypes in db.cargoTypes
                 select cargoTypes;


You can use dynamic, e.g.

protected void baseAdd(dynamic CargoTypes)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜