本文介绍了映射字典< string,string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我有以下数据库结构:


CREATE TABLE [Category]
(
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[WordId] [bigint] NOT NULL,
	[ParentCategoryId] [bigint] NULL,
	PRIMARY KEY ([Id]),
	FOREIGN KEY([ParentCategoryId]) REFERENCES [Category] ([Id]),
	FOREIGN KEY([WordId]) REFERENCES [Word] ([Id])
);

CREATE TABLE [WordTranslation]
(
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[WordId] [bigint] NOT NULL,
	[LanguageCode] [nvarchar](10) NOT NULL,
	[Value] [nvarchar](1000) NOT NULL,
	PRIMARY KEY ([Id]),
	FOREIGN KEY([WordId]) REFERENCES [Word] ([Id])
);

CREATE TABLE [Word]
(
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[Guid] [uniqueidentifier] NOT NULL,
	PRIMARY KEY ([Id])
);


我想针对以下类映射:


namespace A
{
  public interface IEntity
  {
    long Id { get; set; }
  }

  public class Category : IEntity
  {
    public virtual long Id { get; set; }

    public virtual long WordId { get; set; }

    public virtual Word Word { get; set; }

    public virtual long? ParentCategoryId { get; set; }

    public virtual Category ParentCategory { get; set; }

    public virtual ICollection<Category> SubCategories { get; set; }
  }

  public class Word : IEntity
  {
    public virtual long Id { get; set; }

    public virtual Guid Guid { get; set; }

    public virtual IDictionary<string, string> Translations { get; set; }
  }

  public class WordTranslation : IEntity
  {
    public virtual long Id { get; set; }

    public virtual string Value { get; set; }

    public virtual string LanguageCode { get; set; }
  }
}


 

我可以映射类别 - >好一点,没问题。问题是将Word.Translations映射到WordTranslation。

I can map the Category -> Word fine, that's no problem. The problem is mapping the Word.Translations against the WordTranslation.

Translations键应为WordTranslation.LanguageCode,Translations值应为WordTranslations.LanguageCode。

The Translations key should be WordTranslation.LanguageCode and the Translations value should be WordTranslations.LanguageCode.

甚至可以用仅代码/代码优先映射它吗?

Is it even possible to map this with code-only/code-first?

 

我想工作的场景:


// Retrieval
var category = context.Categories.First(x => x.Id == 50);

var englishName = category.Word.Translations["en-US"];
var swedishName = category.Word.Translations["sv-SE"];

// Insertion
category.Word.Translations["en-GB"] = "...";

// This should result in an INSERT INTO [WordTranslation] ([WordId], [LanguageCode], [Value]) VALUES (Word.Id, "en-GB", "...");
context.SaveChanges();


// Kim Johansson

// Kim Johansson

推荐答案

var englishName = category.Word.Transaltions.Single(t => ; t.LanguageCode ==" en-US");

var englishName = category.Word.Transaltions.Single(t => t.LanguageCode == "en-US");


这篇关于映射字典&lt; string,string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:44