I have two Classes:
- Book
- MultilingualString (Which has many Translations, but thats not important for this example)
My goal is to automatically Instantiate the Reference from Book to MultilingualString (Book.Description
).
This is in a relatively complicated application so I reduced it down to the necessary code. The following example shows how my application is interacting with EF:
static void Main(string[] args)
{
using(var model = new ModelCFContext())
{
// Done by a generic ViewModel
var book = model.Set<Book>().Create();
// Currently I am instantiating book.Description inside the ViewModel (of Book in this case).
// Is there a better way?
book.Description = model.MultilingualStrings.Create();
// Set by TextBox-Binding
book.Description.TextDefault = "TestDefault3";
// Done by a generic ViewModel
Insert(model, book);
}
using (var model = new ModelCFContext())
{
OutputFirstBook(model);
}
Console.ReadKey();
}
private static void OutputFirstBook(ModelCFContext model)
{
var spez = model.Books.FirstOrDefault();
Console.WriteLine(spez.Description.TextDefault);
}
private static void Insert<T>(ModelCFContext model, T book) where T : class
{
model.Set<T>().Add(book);
model.SaveChanges();
}
Usually I would instantiate such a reference in the constructor of Book
. But that will not work because EntityFramework will not inject the Proxy (when loading the data from the database).
Book-Class:
[Table("Book")]
public partial class Book
{
public Book()
{
//Description = new MultilingualString();
}
[Key]
public int BookId { get; set; }
[Required]
public virtual MultilingualString Description { get; set; }
}
MultilingualString-Class:
[Table("MultilingualString")]
public partial class MultilingualString
{
public MultilingualString()
{
Translations = new ObservableCollection<Translation>();
}
[Key]
public int MultilingualStringId { get; set; }
public string TextDefault { get; set; }
public virtual ObservableCollection<Translation> Translations { get; set; }
}
I am currently instantiating book.Description in the ViewModel of Book. Is there a nicer way to do that?