简体   繁体   中英

C# Application Settings not saving using custom class

Here's the class im trying to store

 [Serializable]
[XmlRoot(ElementName = "Database", IsNullable = false, Namespace = "http://somesite.com")]

class Database
{
    [XmlAttribute(AttributeName = "Name")]   
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "Provider")]
    public DatabaseProvider Provider { get; set; }

    [XmlAttribute(AttributeName = "Driver")]
    public string Driver { get; set; }

    [XmlElement("DatabaseEntry")]
    public List<DatabaseEntry> SavedEntries { get; set; }

    public Database()
    {
        SavedEntries = new List<DatabaseEntry>();
    }

    public Database(string type, string provider, string driver)
    {

        Name = type;
        Driver = driver;
        Provider = DatabaseProvider.SqlClient;

        Provider = SetProvider(provider);
        SavedEntries = new List<DatabaseEntry>();
    }

    private DatabaseProvider SetProvider(string provider)
    {
        switch (provider)
        {
            case "OleDb":
                return DatabaseProvider.OleDb;
            case "SqlClient":
                return DatabaseProvider.SqlClient;
            default:
                return DatabaseProvider.SqlClient;
        }
    }
}

[Serializable]
[XmlRoot(ElementName = "DatabaseEntry", IsNullable = false, Namespace = "http://somesite.com")]

class DatabaseEntry

{
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "ConnectionString")]
    public string ConnectionString { get; set; }

    [XmlAttribute(AttributeName = "DsnString")]
    public string DsnString { get; set; }

    public DatabaseEntry()
    { }
}

Database is the parent class that I'm trying store, anyone see anything wrong? When I instantiate the class and save it, nothing gets saved. What gives?

EDIT! The code that is being used to save:

if (Settings.Default.SqlDatabase == null) 
   { 
      Settings.Default.SqlDatabase = CreateNewDatabase();
      Settings.Default.Save();
   }

private Database CreateNewDatabase()
{
    Database data = new Database("SQL Server", "SqlClient", "SQL Native Client");
    data.SavedEntries.Add(new DatabaseEntry()
    {
        Name = "Default",
        ConnectionString = @"Hello1",
        DsnString = @"Hello2"
    });
    return data;
}

I'm simply just trying to store an instance of a Database class into the AppSettings

You could try making the classes public - XmlSerializer is fussy about that.

However, I seem to recall that the settings code is much more interested in type-converters; you could try writing a TypeConverter for it?

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