简体   繁体   中英

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. 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.

Mongo db collection

{
"_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:

CredentialId  int
ComputerId    int
Credential    nvarchar(200)

Then for each credential in the array you should create a ComputerCredential entity.

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. It's the power in relational databases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM