SqlNullValueException: данные нулевые. Этот метод или свойство нельзя вызывать для значений Null - PullRequest
0 голосов
/ 29 февраля 2020

Я пытаюсь прочитать данные из заказов Tabe моей базы данных как: return await _context.Order.ToListAsync();

В DataContext выглядит как:

public ProjektContext()
        {
        }

        public ProjektContext(DbContextOptions<ProjektContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Deals> Deals { get; set; }
        public virtual DbSet<Order> Order { get; set; }
        public virtual DbSet<ProductOrderAssignment> ProductOrderAssignment { get; set; }
        public virtual DbSet<Products> Products { get; set; }
        public virtual DbSet<UserAspNetUser> UserAspNetUsers { get; set; }



        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("data source= CONNECTION STRING");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");

            modelBuilder.Entity<Deals>(entity =>
            {
                entity.ToTable("deals");

                entity.Property(e => e.Id).HasColumnName("ID");

                entity.Property(e => e.EndTime)
                    .HasColumnName("endTime")
                    .HasColumnType("date");

                entity.Property(e => e.ProductId).HasColumnName("product_id");

                entity.Property(e => e.ReducedPrice).HasColumnName("reducedPrice");

                entity.Property(e => e.StartTime)
                    .HasColumnName("startTime")
                    .HasColumnType("date");

                entity.HasOne(d => d.Product)
                    .WithMany(p => p.Deals)
                    .HasForeignKey(d => d.ProductId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_deals_products");
            });

            modelBuilder.Entity<Order>(entity =>
            {
                entity.ToTable("order");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.DelivStreetNumber)
                    .HasColumnName("deliv_street_number")
                    .HasMaxLength(10);

                entity.Property(e => e.DelivTown)
                    .HasColumnName("deliv_town")
                    .HasMaxLength(10);

                entity.Property(e => e.DelivZip)
                    .HasColumnName("deliv_zip")
                    .HasMaxLength(10);

                entity.Property(e => e.Delivery)
                    .HasColumnName("delivery")
                    .HasMaxLength(10);

                entity.Property(e => e.PayMethode)
                    .HasColumnName("payMethode")
                    .HasMaxLength(10);

                entity.Property(e => e.UserId).HasColumnName("user_id");

                entity.HasOne(d => d.UserAspNetUser)
                    .WithMany(p => p.Order)
                    .HasForeignKey(d => d.UserId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_order_UserAspNetUser");
            });

            modelBuilder.Entity<ProductOrderAssignment>(entity =>
            {
                entity.ToTable("product_order_assignment");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.Amount).HasColumnName("amount");

                entity.Property(e => e.DealsId).HasColumnName("deals_id");

                entity.Property(e => e.OrderId).HasColumnName("order_id");

                entity.HasOne(d => d.Deals)
                    .WithMany(p => p.ProductOrderAssignment)
                    .HasForeignKey(d => d.DealsId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_product_order_assignment_deals");

                entity.HasOne(d => d.Order)
                    .WithMany(p => p.ProductOrderAssignment)
                    .HasForeignKey(d => d.OrderId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_product_order_assignment_order");
            });

            modelBuilder.Entity<Products>(entity =>
            {
                entity.ToTable("products");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.Delivery).HasColumnName("delivery");

                entity.Property(e => e.Description)
                    .IsRequired()
                    .HasColumnName("description")
                    .HasMaxLength(50);

                entity.Property(e => e.Image)
                    .HasColumnName("image")
                    .HasColumnType("image");

                entity.Property(e => e.InternId)
                    .IsRequired()
                    .HasColumnName("internID")
                    .HasMaxLength(10);

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasColumnName("name")
                    .HasMaxLength(10);

                entity.Property(e => e.NormalPrice).HasColumnName("normalPrice");

                entity.Property(e => e.Weight).HasColumnName("weight");
            });

            modelBuilder.Entity<UserAspNetUser>(entity =>
            {
                entity.ToTable("UserAspNetUser");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.CustomNum)
                    .HasColumnName("customerNum")
                    .HasMaxLength(10);

                entity.Property(e => e.Email)
                    .HasColumnName("email")
                    .HasMaxLength(20);

                entity.Property(e => e.Firstname)
                    .HasColumnName("firstname")
                    .HasMaxLength(10);

                entity.Property(e => e.Gender)
                    .HasColumnName("gender")
                    .HasMaxLength(10);

                entity.Property(e => e.Lastname)
                    .HasColumnName("lastname")
                    .HasMaxLength(10);

                entity.Property(e => e.MemberSince).HasColumnName("memberSince");

                entity.Property(e => e.Password)
                    .HasColumnName("password")
                    .HasMaxLength(10);

                entity.Property(e => e.StreetNumber)
                    .HasColumnName("street_number")
                    .HasMaxLength(20);

                entity.Property(e => e.PhoneNumber)
                    .HasColumnName("telnumber")
                    .HasMaxLength(20);

                entity.Property(e => e.Town)
                    .HasColumnName("town")
                    .HasMaxLength(10);

                entity.Property(e => e.Uidnr)
                    .HasColumnName("UIDNr")
                    .HasMaxLength(10);

                entity.Property(e => e.Zip)
                    .HasColumnName("zip")
                    .HasMaxLength(10);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
} 

два важных класса UserAspNetUser и Order выглядят так:

UserAspNetUser


 public class UserAspNetUser : IdentityUser {
        public UserAspNetUser() {
            Order = new HashSet<Order>();
        }
        public string CustomNum { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Gender { get; set; }
        public string Zip { get; set; }
        public string Town { get; set; }
        public string Street { get; set; }
        public string StreetNumber { get; set; }
        public string Uidnr { get; set; }
        public string Password { get; set; }
        public Nullable<System.DateTime> MemberSince { get; set; }
        public virtual ICollection<Order> Order { get; set; }
    }

Order

 public partial class Order {
        public Order() {
            ProductOrderAssignment = new HashSet<ProductOrderAssignment>();
        }

        public int Id { get; set; }
        public string PayMethode { get; set; }
        public string Delivery { get; set; }
        public string DelivTown { get; set; }
        public string DelivStreetNumber { get; set; }
        public string DelivZip { get; set; }
        public virtual ICollection<ProductOrderAssignment> ProductOrderAssignment { get; set; }
        public string UserId { get; set; }
        public DateTime OrderTime { get; set; }
        public virtual  UserAspNetUser UserAspNetUser { get; set; }
    }

Все остальные контроллеры или рекветы работают хорошо, но если я пытаюсь получить свои заказы с https://localhost:44392/api/orders, я получаю следующие ошибки:

Microsoft.Data.SqlClient.SqlBuffer.get_DateTime()
Microsoft.Data.SqlClient.SqlDataReader.GetDateTime(int i)
lambda_method(Closure , QueryContext , DbDataReader , ResultContext , int[] , ResultCoordinator )
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+AsyncEnumerator.MoveNextAsync()
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync<TSource>(IQueryable<TSource> source, CancellationToken cancellationToken)
API_ProjektKneidinger.Controllers.OrdersController.GetOrder() in OrdersController.cs
-
        }
        // GET: api/Orders
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Order>>> GetOrder() {

            return await _context.Order.ToListAsync();
        }
        // GET: api/Orders/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Order>> GetOrder(int id) {
            var order = await _context.Order.FindAsync(id);
lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

...