473,545 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy Linq objects

Hello,

I'm using LINQ to access a SQL Server database. The user needs to be able to
duplicate a record. Is there an easy way to do this? I rather not have to set
each property from one to the other. I need to copy all the relationships
too.

Thanks for any help, I really appreciate it.

Thanks,
Nick
Jun 27 '08 #1
4 4459
I don't think there is anything built in; however, you can probably
automate much of the work - the following makes a fairly crude (but very
quick) shallow-copy using the default .ctor() [making a point of
ignoring the primary key field(s) - although it isn't really
LINQ-specific] - with the advantage that since this is an extension
method, you could replace on an individual basis by adding a specific
Clone() method to the partial class, and it will be
chosen by the compiler.

using System;
using System.Data.Lin q.Mapping;
using System.Linq;
using System.Linq.Exp ressions;
static class Program
{
static void Main()
{
Foo foo = new Foo { Id = 16, Name = "Fred", DoB = DateTime.Today };
Foo bar = foo.Clone();
}
}
class Foo
{
[Column(IsPrimar yKey = true)] // PK
public int Id { get; set; }
[Column] // test with non-PK ColumnAttribute
public string Name { get; set; }
// test w/o ColumnAttribute
public DateTime DoB { get; set; }
}
public static class ObjectExt
{
public static T Clone<T>(this T obj) where T : new()
{
return ObjectExtCache< T>.Clone(obj);
}
static class ObjectExtCache< Twhere T : new()
{
private static readonly Func<T, Tcloner;
static ObjectExtCache( )
{
ParameterExpres sion param = Expression.Para meter(typeof(T) ,
"in");

var bindings = from prop in typeof(T).GetPr operties()
where prop.CanRead && prop.CanWrite
let column = Attribute.GetCu stomAttribute(p rop,
typeof(ColumnAt tribute))
as ColumnAttribute
where column == null || !column.IsPrima ryKey
select (MemberBinding) Expression.Bind (prop,
Expression.Prop erty(param, prop));

cloner = Expression.Lamb da<Func<T,T>>(
Expression.Memb erInit(
Expression.New( typeof(T)), bindings), param).Compile( );
}
public static T Clone(T obj)
{
return cloner(obj);
}

}
}
Jun 27 '08 #2
Marc,

I'm really late with my reply, but I very much appreciate your help. Your
code was very helpful.

Thanks,
Nick

"Marc Gravell" wrote:
I don't think there is anything built in; however, you can probably
automate much of the work - the following makes a fairly crude (but very
quick) shallow-copy using the default .ctor() [making a point of
ignoring the primary key field(s) - although it isn't really
LINQ-specific] - with the advantage that since this is an extension
method, you could replace on an individual basis by adding a specific
Clone() method to the partial class, and it will be
chosen by the compiler.

using System;
using System.Data.Lin q.Mapping;
using System.Linq;
using System.Linq.Exp ressions;
static class Program
{
static void Main()
{
Foo foo = new Foo { Id = 16, Name = "Fred", DoB = DateTime.Today };
Foo bar = foo.Clone();
}
}
class Foo
{
[Column(IsPrimar yKey = true)] // PK
public int Id { get; set; }
[Column] // test with non-PK ColumnAttribute
public string Name { get; set; }
// test w/o ColumnAttribute
public DateTime DoB { get; set; }
}
public static class ObjectExt
{
public static T Clone<T>(this T obj) where T : new()
{
return ObjectExtCache< T>.Clone(obj);
}
static class ObjectExtCache< Twhere T : new()
{
private static readonly Func<T, Tcloner;
static ObjectExtCache( )
{
ParameterExpres sion param = Expression.Para meter(typeof(T) ,
"in");

var bindings = from prop in typeof(T).GetPr operties()
where prop.CanRead && prop.CanWrite
let column = Attribute.GetCu stomAttribute(p rop,
typeof(ColumnAt tribute))
as ColumnAttribute
where column == null || !column.IsPrima ryKey
select (MemberBinding) Expression.Bind (prop,
Expression.Prop erty(param, prop));

cloner = Expression.Lamb da<Func<T,T>>(
Expression.Memb erInit(
Expression.New( typeof(T)), bindings), param).Compile( );
}
public static T Clone(T obj)
{
return cloner(obj);
}

}
}
Jul 10 '08 #3
No problem,

Marc
Jul 11 '08 #4
Please go to http://www.a2zdotnet.com/Default.aspx
for step by step tutorials for beginers in LINQ sections.

--
regards,
Pankaj
http://www.A2ZDotNet.com
"Nick" wrote:
Hello,

I'm using LINQ to access a SQL Server database. The user needs to be able to
duplicate a record. Is there an easy way to do this? I rather not have to set
each property from one to the other. I need to copy all the relationships
too.

Thanks for any help, I really appreciate it.

Thanks,
Nick
Aug 11 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1332
by: Bob Johnson | last post by:
Just wondering if LINQ might be useful and appropriate in the following scenario: I'm writing a Windows Forms app that enables the user to search for a "client account". The client account is made up of a client number, plus a case number. A given client can have many cases. Here are two clients - the first of which has two cases. 1234-897...
22
10340
by: paululvinius | last post by:
Hi! Testing som Linq-expressions and tried to measure performance and compare it to pre-Linq programming. The folloing two methods are functional equal but the non-Linq one is twice as fast. public List<ConferenceRoomOldWay(int minimumSeatingCapacity) {
8
2107
by: Alcides | last post by:
Hello all, I learn about LINQ here in this forum. I been a VB.NET programmer for quite a while and we are using an internal solution for SQL access. I have some experience with C# and I started to write a blog to share my experiences with a sql framework. I would like to hear some opinions about LINQ, is it the main thing when accessing...
5
3808
by: Andy B | last post by:
I was just wondering, when you create dataContext methods, should you put business logic there to try and minimize pushing data through 2-3 layers of code? or should the business logic still go in another class somewhere making it access the dataContext methods?
7
2660
by: Andy B | last post by:
Just wondering why linq is more useful than datasets? The stuff I do doesn't seem to be too complicated to use linq with it. If I did use linq with it now, I would be doing almost the exact same programming, just with a different data getting process...
9
2491
by: =?Utf-8?B?cmF1bGF2aQ==?= | last post by:
Hi all: after reading different places/sites about linq... I ran into these questions: 1. What framework do we need to run linq ? (does it depend on what version of visual studio we have?) how about vs2008? is it different name space or framework for linq xml or linq sql? ( 2. do we need to have references to what linq's dlls. or...
5
1683
by: ck1 | last post by:
Hi at all - I want to know if there are diffirence with Liqn to SQL and Linq To entity performance. I have read many article on the web that say that Linq To Entity is more fast than Linq To Sql. What is your experience about that ? ck1;
9
2249
by: Cirene | last post by:
I'm about to begin a brand new, big, ASP.NET project (using 3.5 .net fw), VS 2008. I'm using MySQL as the backend (customer request.) I have absolutely no experience with LINQ and/or the Entity Framework. Though I am quite comfortable with ADO.NET and VB.NET. In your opinion, should I take a few days and learn it and utilize these...
0
7479
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7411
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7669
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4962
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1901
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.