[英]How to convert string array property to string to save in the sql server as comma seperated row mongo db to sql server C#
I have a collection in mongo db "computers",I want to retrieve the collect and save it into sql server using Entity framework. 我在mongo db“计算机”中有一个集合,我想使用实体框架检索集合并将其保存到sql服务器中。 The problem is that the collection have an array object.I want to convert it to string and save. 问题是集合有一个数组对象,我想将其转换为字符串并保存。 please help, Thank you. 请帮助,谢谢。 SQL server skips the string [] credentials and inserts rest. SQL Server跳过字符串[]凭据,并插入其余部分。
Mongo db collection Mongo数据库集合
{
"_id": ObjectId('57852fcsdsdsdsd2662a0ce400'),
"machineName": "AAADESKTOP",
"updated": ISODate('2017-05-17T15:09:39.399Z'),
"__v": 111,
"credentials": [
"####################",
"####################",
"#################",
"#####################"
],
"clientVersion": "2.12.2",
"lastActivity": ISODate('2017-05-17T16:30:50.165Z'),
"secret": "####################"
} }
**C# code**
var client = new MongoClient();
var db = client.GetDatabase("Computerdata");
var collection = db.GetCollection<Computers>("computers");
var data = collection.Find(new BsonDocument()).ToListAsync().Result;
foreach (var item in data)
{
EntityFramewrokContext.Computers.Add(item);
EntityFramewrokContext.SaveChanges();
}
public class Computers
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[Key]
public string Id { get; set; }
public string machineName { get; set; }
[BsonDateTimeOptions(Representation = BsonType.DateTime)]
public DateTime updated { get; set; }
public int version { get; set; }
public string[] credentials { get; set; }
public string clientVersion { get; set; }
[BsonDateTimeOptions(Representation = BsonType.DateTime)]
public DateTime lastActivity { get; set; }
public string secretKey { get; set; }
}
If you have a table called Computer
in SQL Server (That you want to write these records to), then you should also create a table called ComputerCredential
that has the following columns: 如果您在SQL Server中有一个名为Computer
的表(要将这些记录写入其中),则还应该创建一个名为ComputerCredential
的表,该表具有以下各列:
CredentialId int
ComputerId int
Credential nvarchar(200)
Then for each credential in the array you should create a ComputerCredential
entity. 然后,应为阵列中的每个凭据创建一个ComputerCredential
实体。
If you desperately want to do it the way you asked. 如果您拼命想按照自己的方式去做。 Then: 然后:
var creds = String.Join(",", computer.credentials);
That will take the array of credentials and make them into a single comma separated string. 这将使用凭据数组,并将它们变成单个逗号分隔的字符串。
When you retrieve the values you can do this: 检索值时,您可以执行以下操作:
var creds = commaSepCredentials.Split(',');
To retrieve the array. 检索数组。 But don't do this, do the first option and learn about relations and joins in SQL Server. 但是不要这样做,请选择第一个选项,并了解SQL Server中的关系和联接。 It's the power in relational databases. 这是关系数据库中的强大功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.