N
N
Nikolai Turnaviotov2013-11-22 20:03:08
.NET
Nikolai Turnaviotov, 2013-11-22 20:03:08

EntityFramework, Linq and very tricky entities. Question on correct writing of CRUD methods in MVC

There are several classes

// основной класс
public MainClass 
{
      public MainClassId { get; set; }
...
      // отношение один ко многим в FluentApi
      public virtual List<SecondClass> SecondClass { get; set; }
}

// список из некоторых свойств для основного обьекта
public SecondClass
{
     public SecondClassId {get; set; }
..
      // отношение один к одному
      [XmlIgnore, ForeignKey("ThirdClass")]
       public Guid ThirdClassId { get; set; }
       public virtual ThirdClass ThirdClass { get; set; }
}

// категория для SecondClass
public class ThirdClass
{
       public Guid ThirdClassId { get; set; }
....
}

Questions:
1. how to correctly write forward and backward links (for example, by a specific Id in ThirdClass, get a list from MainClass, where at least one of the SecondClass elements has a binding to this ThirdClass)
2. How to properly pull all this into a view in MVC via Linq, (I know about View/Editor template views)
3. How to update the resulting model in the Post method Edit(MainClass mainclass) via EF to the database 4. How to correctly delete the MainClass entity with all its connections from SecondaryClass without touching ThirdClass.
5. How to create the MainClass entity, but in such a way that the left ThirdClass entities are not created (at the moment they periodically appear in the application, although I am clearly checking and this should not be)
Now I have CRUD methods that are crutches, the code of which I definitely don’t like, for example, the update code - it actually deletes the old entity (after deleting the SecondClass range from the context) and writes a new entity instead, obtained from the Post method
By the way, the EF masters have a question - tell me a good article / book / something else, where the material is written on the correct work with Linq, MS SQL, tricky entities

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VanHelSeenG, 2014-11-02
@VanHelSeenG

Let's start from the beginning:
Small amendments to the class, so that it is clear what and how it should actually be

// основной класс
public MainClass 
{
      public MainClassId { get; set; }
...
      // отношение один ко многим в FluentApi
     [InverseProperty("MainClassProp")] //обратная связь
      public virtual List<SecondClass> SecondClass { get; set; }
}

// список из некоторых свойств для основного обьекта
public SecondClass
{
     public SecondClassId {get; set; }
    [InversePropert("SecondClass")] //указываем на связь со списком
    public MainClass MainClassProp
..
      // отношение один к одному
      [XmlIgnore]
       public Guid ThirdClassId { get; set; }
       [ForeignKey("ThirdClass")] //правильно делать так - указываем на переменную, того же типа, что и ключевое в ThirdClass, для MainClass тоже можно сделать
       public virtual ThirdClass ThirdClass { get; set; }
}

// категория для SecondClass
public class ThirdClass
{
       public Guid ThirdClassId { get; set; }
....
}

You can also read about relationships here, everything is very detailed and in Russian
1.
db.MainClasses.Include(s => s.SecondClass).Where(cl => cl.SecondClass.Any(s => s.ThirdClassId == %что-то%);

(For .Include() , you need to connect the namespace using System.Data.Entity, it is needed so that EF immediately loads the table with SecondClasses)
2. Already, I think the answer is clear, you just need to figure it out further
deletion, for example
DataContext overload method
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//тут строится такая конструкция
modelBuilder.Entity<MainClass>().HasMany(m => m.SecondClass).WithRequired(s => s.MainClassProp).WIllCascadeOnDelete();
//а чтобы не удалялись Third class
modelBuilder.Entity<SecondClass>().HasOptional(или Required)(s => s.ThirdClass).WillCascadeOnDelete(false);
}

4 (aka 5). In order not to create new ThirdClass entities, you need to explicitly specify a link to ThirdClass so that EF understands the relationship, that is, in advance, you need to make a selection
var res = db.ThirdClasses.FirstOrDefault(t => t.ThirdClassId ==%giud%);
if (res != null)
secondClass.ThirdClass = res;

PS in fact, there are a bunch of different articles on the site. And so, here's another article:
msdn.microsoft.com/ru-ru/data/jj591621.aspx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question