TranslationItem模型:
[DataContract]
public class TranslationItem : CloneableBaseEntity<TranslationItem>, IValidatableObject
{
public int TranslationId { get; set; }
public Translation Translation { get; set; }
public int Lcid { get; set; }
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
RaisePropertyChanged("Text");
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var t = validationContext.ObjectInstance as TranslationItem;
return t.Translation.Validate(validationContext);
}
}
翻译模型:
[DataContract]
public class Translation : CloneableBaseEntity<Translation>, IValidatableObject
{
private static int _englishLcid = 9;
private ObservableCollection<TranslationItem> _translations;
[DataMember]
public virtual ObservableCollection<TranslationItem> Translations
{
get{
return _translations;
}
set
{
_translations = value;
foreach (TranslationItem ti in _translations)
{
ti.PropertyChanged += ti_PropertyChanged;
}
}
}
...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext){
Translation t;
if(validationContext.ObjectInstance.GetType()== typeof(Translation))
t = validationContext.ObjectInstance as Translation;
else
t =( validationContext.ObjectInstance as TranslationItem).Translation;
if (!t.EnglishNotRequried)
{
if (!t.TranslationDict.ContainsKey(_englishLcid) || String.IsNullOrEmpty(t.TranslationDict[_englishLcid].Text))
{
yield return new ValidationResult("EnglishTranslationMissing");
}
}
}
}
我的迁移配置类中的Seed方法
protected override void Seed(DbContext context)
{
int deLcid = new CultureInfo("en").LCID;
int enLcid = new CultureInfo("en").LCID;
TranslationItem enStd = context.TranslationItems.FirstOrDefault(ti => ti.Text == "Standard" && ti.Lcid == enLcid)
?? new TranslationItem { Text = "Standard", Lcid = enLcid };
TranslationItem deStd = context.TranslationItems.FirstOrDefault(ti => ti.Text == "Standard" && ti.Lcid == deLcid)
?? new TranslationItem { Text = "Standard", Lcid = deLcid };
context.Translations.AddOrUpdate(
t => t.Translations,
new Translation
{
Translations = new ObservableCollection<TranslationItem>
{
enStd,
deStd
}
});
context.SaveChanges();
context.EventTypes.AddOrUpdate(
et => et.Name,
new EventType
{
Name = context.Translations.FirstOrDefault(t => t.Translations.Any(x => x.Lcid == enLcid && x.Text == "Standard") &&
t.Translations.Any(x => x.Lcid == deLcid && x.Text == "Standard") )
});
}
当我想更新数据库
时,我收到以下错误Unable to create a constant value of type 'PQS.Model.TranslationItem'. Only primitive types or enumeration types are supported in this context.
我不太确定如何解决这个问题。
我已经尝试首先插入我的TranslationItems,但是当我这样做时,验证失败,因为我猜想需要翻译FK。
请帮助!!
答案 0 :(得分:1)
通过我自己的一个小黑客修复它(不完全是我的首选解决方案,但现在可以使用)
我的问题:似乎使用AddOrUpdate(...)
我只能比较原始类型或枚举类型。
所以我添加了一个名为SeedId
的额外ID来识别我的实体。
所以我的种子方法中的代码现在非常简单:
foreach (EventType eventtype in PqsDbContext.getStdEventTypes())
{
context.EventTypes.AddOrUpdate(et => et.SeedId, eventtype);
}