Duplicate LINQ to SQL entity / record?(重复 LINQ to SQL 实体/记录?)
问题描述
复制 [克隆] LINQ to SQL 实体从而在数据库中生成新记录的最佳实践是什么?
What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?
上下文是我希望为管理员网格中的记录创建一个重复的函数.网站并在尝试了一些显而易见的事情后,读取数据,更改 ID=0,更改名称,submitChanges(),然后遇到异常,哈哈.我想我可能会停下来问问专家.
The context is that I wish to make a duplicate function for records in a grid of an admin. website and after trying a few things and the obvious, read data, alter ID=0, change name, submitChanges(), and hitting an exception, lol. I thought I might stop and ask an expert.
我希望首先读取记录,通过添加前缀Copy Of"更改名称,然后另存为新记录.
I wish to start with first reading the record, altering the name by prefixing with "Copy Of " and then saving as a new record.
推荐答案
创建一个新实例,然后使用 linq 映射类和反射来复制成员值.
Create a new instance and then use the linq mapping classes together with reflection to copy member values.
例如
public static void CopyDataMembers(this DataContext dc,
object sourceEntity,
object targetEntity)
{
//get entity members
IEnumerable<MetaDataMember> dataMembers =
from mem in dc.Mapping.GetTable(sourceEntity.GetType())
.RowType.DataMembers
where mem.IsAssociation == false
select mem;
//go through the list of members and compare values
foreach (MetaDataMember mem in dataMembers)
{
object originalValue = mem.StorageAccessor.GetBoxedValue(targetEntity);
object newValue = mem.StorageAccessor.GetBoxedValue(sourceEntity);
//check if the value has changed
if (newValue == null && originalValue != null
|| newValue != null && !newValue.Equals(originalValue))
{
//use reflection to update the target
System.Reflection.PropertyInfo propInfo =
targetEntity.GetType().GetProperty(mem.Name);
propInfo.SetValue(targetEntity,
propInfo.GetValue(sourceEntity, null),
null);
// setboxedvalue bypasses change tracking - otherwise
// mem.StorageAccessor.SetBoxedValue(ref targetEntity, newValue);
// could be used instead of reflection
}
}
}
...或者您可以使用 DataContractSerializer 克隆它:
...or you can clone it using the DataContractSerializer:
internal static T CloneEntity<T>(T originalEntity) where T : someentitybaseclass
{
Type entityType = typeof(T);
DataContractSerializer ser =
new DataContractSerializer(entityType);
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, originalEntity);
ms.Position = 0;
return (T)ser.ReadObject(ms);
}
}
这篇关于重复 LINQ to SQL 实体/记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重复 LINQ to SQL 实体/记录?
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
