Błędne klucze w CodeFirst

0

Witam serdecznie.

Mam problem z kluczami w CodeFirst.

W momencie, gdy próbuję zalogować się jak użytkownik wywala mi błąd:

The property 'UserId' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection<T> where T is a valid entity type.

using (var db = new ShopContext())
            {
               var user = db.Users.FirstOrDefault(u => u.Email == email);
                
              if (user != null)
 

Mam taki model dla Usera:

 
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public enum ActivationStatus // czy konto aktywne
    {
        Yes, No
    }

    public enum UserRoles
    {
        Normal, Administrator, Disabled
    }

    public class User
    {
        [Key]
        public int UserId { get; set; }
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
        public string Email { get; set; }
        public string UserAvatarUrl { get; set; } // avatar dla zarejestrowanego użytkownika
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string PhoneNumber { get; set;  }
        public DateTime RegistrationDate { get; set; }
        public ActivationStatus IsActivated { get; set; } // czy konto zostało aktywowane ( 1 - tak, 0 - nie )
        public int DiscountPoints { get; set; } // suma wszystkich punktów zniżki za zakupy
        public UserRoles RoleOfUser { get; set; } // rola dla użytkownika

        [ForeignKey("Address")]
        public int AddressId { get; set; }
        public virtual Address Address { get; set; }

    }
}

I model dla Adresu:

 
using System.ComponentModel.DataAnnotations;

namespace SklepInternetowyMVC.Models
{
    public class Address
    {
        [Key]
        public int AddressId { get; set; } 
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string StreetName { get; set; }
        public string FlatNumber { get; set; }
    }
}

Co robię źle?

Metoda do logowania jest tutaj:

 
[HttpPost]
        public ActionResult Login(LoginViewModel user)
        {
            if (ModelState.IsValid)
            {
                if (IsValid(user.Email, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.Email, false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("","Dane logowania sa nie prawidlowe");
                }
            }
            return View();
        }

Bardzo proszę o pomoc :)

0

wydaje mi się że w tabeli address powinieneś mieć pole userID
po drugie nie podoba mi się też ustawianie id o nazwie UserId/ AddressId. lepiej moim zdaniem ustawić nazwę na Id

0

Ale co gdy w przypadku jakieś tabele połączone są relacjami, a klucze w obu tabelach nazywane są ID ?

0

no ale to są różne tabele ;) to tak samo jak masz dwie klasy ale w środku masz np. pole int licznik;. to nie ma znaczenia. będziesz robił coś takiego potem:

void blablabla(int id)
.....FirstOrDefault(x => x.Employee.Id == id).

0

Ok poprawiłem te klucze i w każdej tabeli ustawiłem sobie Primary Key jako Id.

Natomiast nie udało mi się nadal rozwiązać mojego problemu :(

Mam 7 modeli i zadeklarowanych 7 DbSetów bo chce robić w Code First.
Do tego dorobiłem sobie ShopInicjalizer.cs w którym na sztywno dodaje obiekty do tej bazy.

Chce się zalogować jako dodany użytkownik i wywala mi ten błąd z kluczami nawigacyjnymi:

The property 'UserId' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection<T> where T is a valid entity type.



Wiersz 102:            using (var db = new ShopContext())
Wiersz 103:            {
Wiersz 104:                var user = db.Users.FirstOrDefault(u => u.Email == email);
Wiersz 105:                
Wiersz 106:                if (user != null)
 

Model dla Usera wygląda tak:

 
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public enum ActivationStatus // czy konto aktywne
    {
        Yes, No
    }

    public enum UserRoles
    {
        Normal, Administrator, Disabled
    }

    public class User
    {
        [Key]
        public int Id { get; set; }
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
        public string Email { get; set; }
        public string UserAvatarUrl { get; set; } // avatar dla zarejestrowanego użytkownika
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string PhoneNumber { get; set;  }
        public DateTime RegistrationDate { get; set; }
        public ActivationStatus IsActivated { get; set; } // czy konto zostało aktywowane ( 1 - tak, 0 - nie )
        public int DiscountPoints { get; set; } // suma wszystkich punktów zniżki za zakupy
        public UserRoles RoleOfUser { get; set; } // rola dla użytkownika

        [ForeignKey("Address")]
        public int AddressId { get; set; }
        public virtual Address Address { get; set; }

    }
}

Model dla Addresu wygląda tak:


using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public class Address
    {
        [Key]
        public int Id { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string StreetName { get; set; }
        public string FlatNumber { get; set; }

        [ForeignKey("User")]
        public int UserId { get; set; }
        public virtual User User { get; set; }               
    }
}

 

Tak wygląda tabela Orders:

 
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public class Order
    {
        [Key]
        public int Id { get; set; }
        public uint ProductCount { get; set; } // ilosc zamówień
        public DateTime OrderDate { get; set; } // data konkretnego zamówienia
        public uint OrderDiscountPoints { get; set; } // punkty zniżki dla danego zamówienia

        [ForeignKey("UserId")]
        public int UserId { get; set; }
        public List<Product> ProductList { get; set; }
    }
}

Tak OrderDetails:

 
using System.ComponentModel.DataAnnotations;

namespace SklepInternetowyMVC.Models
{
    public class OrderDetail
    {
        [Key]
        public int Id { get; set; }
        public Order Order { get; set; }
        public Product Product { get; set; }
        public int ProductCount { get; set; }
    }
}

Product:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace SklepInternetowyMVC.Models
{
    public class Product
    {
        [Key]
        public int Id { get; set; }
        public string ProductName { get; set; } // nazwa produktu

        public List<ProductCategory> ProductCategories { get; set; }
        public decimal ProductPrice { get; set; } // cena produktu
        public uint ProductCount { get; set; } // ilość produktu

        public Suplier Suplier { get; set; }
        public string ProductImageUrl { get; set; } // zdjecie dla produktu
        public string ProductDescriptionText { get; set; } // opis produktu
        public double ProductCalority { get; set; } // kalorycznosc
        public double ProductCarbohydrates { get; set; } // zawartosc weglowodanów
        public double ProductProteins { get; set; } // zawartość białka
        public double ProductFat { get; set; } // zawartość tłuszczu
    }
}
 

ProductCategory:

 
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public enum Category
    {
        Pieczywo, Zioła, Suplementy, Herbaty, Przetwory, Wędliny, Owoce, Warzywa, Soki, Nasiona, Nabiał, Pozostałe
    }

    public class ProductCategory
    {
        [Key]
        public int Id { get; set; }

        public string CategoryName { get; set; } // nazwa kategorii produktu
        public string CategoryDescription { get; set; } // opis wybranej kategorii
        public string CategoryImageUrl { get; set; } // obrazek dla daneh kategorii
    }
}

I ostatnia Suplier:

 
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace SklepInternetowyMVC.Models
{
    public class Suplier
    {
        [Key]
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public List<Address> CompanyAddresses { get; set; } 
    }
}

ShopContext wygląda tak:

 
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Diagnostics;
using SklepInternetowyMVC.Models;

namespace SklepInternetowyMVC.DAL
{
    public class ShopContext : DbContext
    {
        public ShopContext()
            : base(@"Data Source=nazwaserwera;Initial Catalog=SklepInternetowyMVC;Integrated Security=True")
        {
            
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductCategory> ProductCategories { get; set; }
        public DbSet<Suplier> Supliers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

A ShopInitializer.cs tak:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using SklepInternetowyMVC.Models;

namespace SklepInternetowyMVC.DAL
{
    public class ShopInitializer : DropCreateDatabaseIfModelChanges<ShopContext>
    {
        protected override void Seed(ShopContext context)
        {
            var usr = new List<User>
            {
                new User
                { 
                    FirstName = "Józel", LastName = "Trombala", Age = 33,
                    Password = "admin123", PhoneNumber = "545656767",
                    DiscountPoints = 360, Email = "[email protected]", Gender = "Mężczyzna", 
                    IsActivated = ActivationStatus.Yes, RegistrationDate = DateTime.Now,
                    RoleOfUser = UserRoles.Administrator, Address = new Address {City = "Poznań", PostalCode = "70-700", FlatNumber = "34", StreetName = "Polna"}
                },
            
            };
            usr.ForEach(u => context.Users.Add(u));
            context.SaveChanges();

            var ord = new List<Order>
            {
                new Order
                {
                   OrderDate = DateTime.Now, OrderDiscountPoints = 10, ProductCount = 4, ProductList = new List<Product>()
                },
            };
            ord.ForEach(o => context.Orders.Add(o));
            context.SaveChanges();

            var ordDet = new List<OrderDetail>
            {
                new OrderDetail
                {
                    Order = new Order(), Product = new Product(), ProductCount = 4
                },
            };
            ordDet.ForEach(od => context.OrderDetails.Add(od));
            context.SaveChanges();

            var prod = new List<Product>
            {
                new Product
                {
                    ProductCount = 234, ProductCategories = new List<ProductCategory>(), 
                    ProductCalority = 345, ProductCarbohydrates = 34, ProductDescriptionText = "jakies przykładowe pieczywo",
                    ProductFat = 34, ProductImageUrl = "", ProductName = "Chleb wiejski", ProductPrice = 3.14m , ProductProteins = 234, Suplier = new Suplier()
                },
            };
            prod.ForEach(p => context.Products.Add(p));
            context.SaveChanges();

            var prodcat = new List<ProductCategory>
            {
                new ProductCategory
                {
                    CategoryDescription = "jaskakss", CategoryImageUrl = "", CategoryName = Category.Pieczywo.ToString(), 
                },
            };
            prodcat.ForEach(p => context.ProductCategories.Add(p));
            context.SaveChanges();

            var sup = new List<Suplier>
            {
                new Suplier
                {
                    CompanyAddresses = new List<Address>(), CompanyName = "Remondis"
                },
            };
            sup.ForEach(s => context.Supliers.Add(s));
            context.SaveChanges();
        }
    }
}
 

Dałem sobie tam na razie DropCreateTablesIfModelsChanges.

Jak mam zadeklarować te klucze, żeby mi to wszystko działało? Bardzo proszę o pomoc :(

Inna sprawą jest jeszcze fakt, że nie wiem czy ta tabela mi się generuje.
Niby w Server Managerze jest ale nie ma w sobie tabel.

user image

0

wiem chyba. Masz na górze takie coś:

[ForeignKey("UserId")]
        public int UserId { get; set; }

zamiast tego daj

 [ForeignKey("Id")]
        public virtual User User { get; set; }
0

Też tak robiłem i nic to nie dało :(

1

Zaczalbym na twoim miejscu od usuniecia wszystkich zbednych atrybutow i zaczecia czytania o konwencjach EF.

Blad wystepuje poniewaz atrybut ForeignKey sluzy do oznaczania wlasciwosci typow encyjnych jako klucze obce, a nie typow prymitywnych. Stosuje sie go tylko wtedy, jesli mamy 2 powiazania do tego samego typu, przyklad:

public class Something {
  public int SomethingImportantId1 { get; set; }
  public int SomethingImportantId2 { get; set; }

  [ForeignKey("SomethingImportantId1")]
  public SomethingImportant Navigation1 { get; set; }

  [ForeignKey("SomethingImportantId2")]
  public SomethingImportant Navigation2 { get; set; }
}
0

Czyli wywalić te klucze obce i np jak mam tabele User i Address to jeśli mój user ma 1 adres to w tabeli user dodać sobie

public virtual Address Address { get; set; }

A w tabeli User

public virtual User User { get; set; } ?

0

Nie usuwaj pol kluczy, tylko usun atrybuty, a klucze wraz z wlasciwosciami nawigacyjnymi nazywaj tak:

public class User {
  public int AddressId { get; set; }
  public virtual Address Address { get; set; }
}
  • Co do twojego przykladu, to chyba probujesz zrobic jakos nieudolnie powiazanie 1:1, ktore tutaj:
    #Jest bledne (przynajmniej tak mi sie wydaje, nie znam modelu twojego biznesu)
    #Nie zadziala w ten sposob.

Jesli chcesz zrobic, zeby 1 adres mogl byc przypisany tylko do 1 uzytkownika, to najlepiej to zrobic, robiac klase Address jako ComplexType. Wtedy wszystkie pola klasy Address zostana wrzucone jako kolumny w tabeli uzytkownicy.

Natomiast (IMO) sensowniej (sensowniej glupio brzmi, sam zrobilbym tak jak jest powyzej, ten przyklad na wypadek, gdy koniecznie potrzebujesz miec encje Address) jest, gdy mozesz miec kilku uzytkownikow z tego samego adresu, wtedy robisz standardowo.

public virtual ICollection<User> Users { get; set; }
0

Ok zostawiłem i klucze normalne i virtuale i aktualnie mam taki błąd :

Unable to determine the principal end of an association between the types 'SklepInternetowyMVC.Models.User' and 'SklepInternetowyMVC.Models.Address'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

W modelu Usera mam tak:

        public int AddressId { get; set; }
        public virtual Address Address { get; set; } 

W modelu Addressu mam tak:

        public int UserId { get; set; }
        public virtual User User { get; set; }       

A to ICollection<User> wstawić do Addresu i również dodać sobie w tabeli User ICollection<Address> ?
Jak to się później inicjalizuje takie ICollection<T> w Inicjalizerze?

Musze tu chyba zrobić fluent API albo DataAnnotation cokolwiek to jest :P

0

Jesli chcesz robic relacje 1:N, to gdzies musi byc 1, a gdzies musi byc to N.

public class User {
  public int AddressId { get; set; }
  public virtual Address Address { get; set; }
}

public class Address {
  public virtual ICollection<User> Users { get; set; }
}

Co sie tlumaczy na:
#Kazdy uzytkownik moze miec 1 adres.
#Kazdy adres moze miec N uzytkownikow.

Ok czyli nad klasami dopisze sobie [ComplexType] i powinno zagrać?

public class User {
  public Address Address { get; set; }
}

[ComplexType]
public class Address {
  // ...
}
0

Ok zrobiłem model User i Address jako komplex type i teraz wrzeszczy o takie coś:

 The type 'Address' has already been configured as an entity type. It cannot be reconfigured as a complex type.

Address:

  [ComplexType]
    public class Address
    {
        [Key]
        public int Id { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string StreetName { get; set; }
        public string FlatNumber { get; set; }

        public int UserId { get; set; }
        public virtual ICollection<User> User { get; set; }       
    }

User:

 using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SklepInternetowyMVC.Models
{
    public enum ActivationStatus // czy konto aktywne
    {
        Yes, No
    }

    public enum UserRoles
    {
        Normal, Administrator, Disabled
    }

    [ComplexType]
    public class User
    {
        [Key]
        public int Id { get; set; }
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
        public string Email { get; set; }
        public string UserAvatarUrl { get; set; } // avatar dla zarejestrowanego użytkownika
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string PhoneNumber { get; set;  }
        public DateTime RegistrationDate { get; set; }
        public ActivationStatus IsActivated { get; set; } // czy konto zostało aktywowane ( 1 - tak, 0 - nie )
        public int DiscountPoints { get; set; } // suma wszystkich punktów zniżki za zakupy
        public UserRoles RoleOfUser { get; set; } // rola dla użytkownika

        public int AddressId { get; set; }
        public virtual Address Address { get; set; } 

    }
}
0

ComplexType to zwykla struktura! Nie ma zadnych kluczy, jest wstawiana jak leci do tabeli jakiejs encji! Klasa User nie moze byc ComplexType. Chlopie wez poczytaj cos o tym EF...

0

Sporo czytam ale możliwości jest na prawdę sporo a nie wiem jak to zrobić żeby działało :P

Chciałbym zostawić te klasy tak jak są może bez tych complex type.

A może fluent mapping do tego zrobić?

0

Wywaliłem ten complextype i po próbie zalogowania się mam taki błąd:

Obiektu typu 'SklepInternetowyMVC.DAL.ShopContext' nie można przekonwertować na typ 'System.Data.Entity.IDatabaseInitializer`1[SklepInternetowyMVC.DAL.ShopContext]'. 
0
    public class User
    {
        public int Id { get; set; }
        public string Password { get; set; }
        public string PasswordSalt { get; set; }
        public string Email { get; set; }
        public string UserAvatarUrl { get; set; } // avatar dla zarejestrowanego użytkownika
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string PhoneNumber { get; set;  }
        public DateTime RegistrationDate { get; set; }
        public ActivationStatus IsActivated { get; set; } // czy konto zostało aktywowane ( 1 - tak, 0 - nie )
        public int DiscountPoints { get; set; } // suma wszystkich punktów zniżki za zakupy
        public UserRoles RoleOfUser { get; set; } // rola dla użytkownika

        public virtual Address Address { get; set; } 
    }

    [ComplexType]
    public class Address
    {
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string StreetName { get; set; }
        public string FlatNumber { get; set; }
    }

Po prostu wstaw cos takiego, a nie cuduj.

0

No mom coś takiego identyczne :)

I dalej jest taki błąd :

The type 'Address' has already been configured as an entity type. It cannot be reconfigured as a complex type. 
0

Hmm... Jesli wywalalo Ci sie przed odpaleniem appki/w czasie inicjalizacji to juz to naprawilem. Pozmienialem tylko to o czym tluklem przez ostatnie kilka postow. Nie mam pojecia czy chciales pulla, wiec wrzucam tutaj jako archiwum to co zmienialem.

Na przyszlosc, to mozesz wrzucic link do repo w posta, bedzie prosciej.

0

Nie przed odpaleniem tylko w momencie gdy chciałem się zalogować na użytkownika, który jest dodany w inicjalizerze :) Już sprawdzam :)

0

Wprowadziłem to co mi przesłałeś ale tym razem podczas logowania dostaje taki błąd:

One or more validation errors were detected during model generation:

SklepInternetowyMVC.DAL.Address: : EntityType 'Address' has no key defined. Define the key for this EntityType.
Addresses: EntityType: EntitySet 'Addresses' is based on type 'Address' that has no keys defined. 
0

Zapomnialem wyrzucic DbSet<Address> ... z kontekstu. + Musisz zmienic sposob tworzenia obiektow na zwyczajne new.

Wieczorem ci to przetestuje w calosci, na razie nie mam dostepu do zadnego serwera sql.

0

W jakim sensie na zwyczajne new? W inicjalizerze to zmienić?

A jak zakomentuje DbSeta<Address> to w AccountControllerze nie bede mógł dodawać adresu tak jak dodawałem:

 var sysUserAddres = db.Addresses.Create(); 
0

W takim sensie:

user.Address = new Address {
  //...
}
0

ComplexType to nie tabela (nie robisz dla niego DbSeta) tylko wygodny sposob na przedstawienie dodatkowy pól w tabeli, ktora uzywa tego ComplexType.
Poczytaj troche o EF...

0

Okej, przyjrzalem sie troche bardziej temu projektowi, 2 pierwsze rzeczy, ktore powoduja 99% problemow.
1.

<context type="SklepInternetowyMVC.DAL.ShopContext, SklepInternetowyMVC">
  <databaseInitializer type="SklepInternetowyMVC.DAL.ShopContext, SklepInternetowyMVC" />
</context>

Ustawiasz, zeby twoj kontekst byl inicjaliizerem bazy, to po prostu nie przejdzie.

  1. Cala te encje sa w duzej mierze bezsensu, stad bezsensu jest poprawianie tego na cokolwiek.

Moje rady:

  1. Napisz projekt bazy (wyklikaj w jakims Sql Server MS) na sucho, wrzuc na forum do odpowiedniej kategorii, na pewno ktos madrzejszy ode mnie sie wypowie.
  2. Zapoznaj sie z podstawami EF (przejrzyj jakis tutorial w internetach, nie zajmie to wiecej niz 1-kilka dni).
  3. Napisz calosc od nowa, tym razem z glowa.

Z aktualnym stanem naprawde nie ma sensu sie meczyc, bo w gruncie rzeczy i tak by to musial ktos przepisac i tak.

0

Nie ma sensu tego milion razy przepisywać.

Poprawiłem ten kontext oraz connection stringa i teraz ładnie mi wygenerowało tabele do bazy do której wreszcie mam podgląd.
Dane z inicjalizera również się do niej dodały.

0

Walcze teraz z tym logowaniem. Bo jest jakiś problem z tym SimpleCrypto.

The salt was not in an expected format of {int}.{string}

 Wiersz 31:                 if (user != null)
Wiersz 32:                 {
Wiersz 33:                     if (user.Password == crypto.Compute(password, user.Password))
Wiersz 34:                     {
Wiersz 35:                         isValid = true;

Tak jakby format potwierdzenia hasła się nie zgadzał.

user image

W bazie jest NULLEM a powinien wpisać tam zahashowaną wartość, odkodować ją i porównać.

Tak wygląda moja funkcja IsValid()

 // funkcja do walidacji danych logowania
        public bool IsValid(string email, string password)
        {
            var crypto = new SimpleCrypto.PBKDF2();
            bool isValid = false;

            using (var db = new ShopContext())
            {
                var user = db.Users.FirstOrDefault(u => u.Email == email);

                if (user != null)
                {
                    if (user.Password == crypto.Compute(password, user.Password))
                    {
                        isValid = true;
                    }
                }
            }
            return isValid;
        } 
0

Ok poprawiłem co nieco. Teraz SALT dodaje się do bazy i ustawiłem, żeby kasował i tworzył bazę za każdym razem.

user image

0

Teraz hasło jest również hashowane tylko nie wiem czy długościowo się to zgadza bo ono ma 32 znaki a salt 16 :P

user image

 
 var usr = new List<User>
            {
                new User
                { 
                    FirstName = "Adam", LastName = "Kawik", Age = 23,
                    Password = Crypto.Hash("admin123"),PasswordSalt = Crypto.GenerateSalt(), PhoneNumber = "506715343",
                    DiscountPoints = 360, Email = "[email protected]", Gender = "Mężczyzna", 
                    IsActivated = ActivationStatus.Yes, RegistrationDate = DateTime.Now,
                    RoleOfUser = UserRoles.Administrator, Address = new Address {City = "Skoczów", PostalCode = "43-430", StreetName = "Łęgowa", FlatNumber = "29" }
                },
            
            };
            usr.ForEach(u => context.Users.Add(u));
            context.SaveChanges();

Teraz mam jakiś problem z Datami jak chce się zalogować:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated. 

Wiersz 44:             };
Wiersz 45:             ordDet.ForEach(od => context.OrderDetails.Add(od));
Wiersz 46:             context.SaveChanges();
Wiersz 47: 
Wiersz 48:             var prod = new List<Product> 

W moim inicjalizerze wygląda to tak:

  var ordDet = new List<OrderDetail>
            {
                new OrderDetail
                {
                    Order = new Order(), Product = new Product(), ProductCount = 4
                },
            };
            ordDet.ForEach(od => context.OrderDetails.Add(od));
            context.SaveChanges();

Chce aby automatycznie wpisał mi Datetime.Now do bazy żeby nie musieć tego podawać " z palca "

1 użytkowników online, w tym zalogowanych: 0, gości: 1