سؤال

I'm using the CultureInfo class to describe the language of localizable data in my application.

class LocalizedText
{
    public int Id { get; set; }

    public string Text { get; set; }

    public CultureInfo Language { get; set; }
}

Now I'd like to map the above class to a database table, using a code first approach.

Sample data:

 +----+------------------------+----------+
 | Id | Text                   | Language |
 +----+------------------------+----------+
 |  1 | Hello World!           | en       |
 +----+------------------------+----------+
 |  1 | Hallo Welt!            | de       |
 +----+------------------------+----------+
 |  1 | Bonjour tout le monde! | fr       |
 +----+------------------------+----------+

I thought this would be easy enough to do using the Fluent API in EF6, but I guess it's not.

What I've tried:

modelBuilder.Entity<CultureInfo>()
            .HasKey(info => info.TwoLetterISOLanguageName);

But then I get an error. Presumably because CultureInfo.TwoLetterISOLanguageName is read-only.

The key component 'TwoLetterISOLanguageName' is not a declared property on type 'CultureInfo'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

So can this be done at all?

هل كانت مفيدة؟

المحلول

You cannot map CultureInfo class to column in database. But you can ignore this property and create another string property which will be mapped:

modelBuilder.Entity<LocalizedText>()
    .Ignore(lt => lt.Language);

modelBuilder.Entity<LocalizedText>()
    .Property(lt => lt.TwoLetterISOLanguageName)
    .HasColumnName("Language");

And then just set Language property when TwoLetterISOLanguageName is assigned:

public class LocalizedText
{
    public int Id { get; set; }
    public string Text { get; set; }
    public CultureInfo Language { get; set; }

    public string TwoLetterISOLanguageName
    {
      get { return Language == null ? null : Language.TwoLetterISOLanguageName; }
      set { Language = CultureInfo.GetCultureInfo(value); }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top