program story

값은 null 일 수 없습니다.

inputbox 2020. 8. 5. 08:13
반응형

값은 null 일 수 없습니다. 매개 변수 이름 : 소스


이것은 아마도 오랫동안 해결하는 데 몇 시간을 소비 한 가장 큰 시간 낭비 문제 일 것입니다.

var db = new hublisherEntities();
establishment_brands est = new establishment_brands();

est.brand_id = 1;
est.establishment_id = 1;
est.price = collection["price"];
est.size = collection["size"];

db.establishment_brands.Add(est);
db.SaveChanges();

이것은 나에게 오류를 준다

값은 null 일 수 없습니다. 매개 변수 이름 : 소스

의 스택 추적

[ArgumentNullException : 값은 null 일 수 없습니다. 매개 변수 이름 : source] System.Linq.Enumerable.Any (IEnumerable 1 source, Func2 술어) +4083335 System.Data.Entity.Internal.InternalContext.WrapUpdateException (UpdateException updateException) +87
System.Data.Entity.Internal.InternalContext.SaveChanges () + 193
System.Data.Entity.Internal.LazyInternalContext.SaveChanges () +33
System.Data.Entity.DbContext.SaveChanges () +20 ... ...

테이블에 엔터티를 추가하고 싶습니다. ORM은 EF입니다.


나는 이것을 잠시 동안 가지고 있었고, 대답은 반드시 당신이 기대하는 것이 아닙니다. 연결 문자열이 잘못되면이 오류 메시지가 자주 나타납니다.

추측에 따르면 다음과 같은 것이 필요합니다.

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

일어나고있는 일은 잘못된 장소에서 데이터 소스를 찾고 있다는 것입니다. Entity Framework는 약간 다르게 지정합니다. 연결 문자열과 EF 구성을 게시하면 확인할 수 있습니다.


DbContext 내부 어딘가에있는 값 IEnumerable과 함께 쿼리 Any()(또는 Where()또는 Select()또는 다른 LINQ 메소드)하지만,이 값이다 null.

LINQ- 방법을 사용하거나 IEnumerableNULL 인 매개 변수로 쿼리를 함께 사용했는지 (예제 코드 외부에) 쿼리를 작성했는지 확인하십시오 .


내 이유는 여기의 나머지 부분과 다르 므로이 문제가있는 다른 사람을 위해 게시 할 것이라고 생각했습니다.

null 필터로 DbSet 인스턴스에서 Count를 호출했습니다.

dbSet.Count(null);

여기에 null을 전달하면 오류가 발생하므로 필터가 null 인 경우 매개 변수가없는 메서드를 호출합니다.

 if (filter == null)
 {
     return dbSet.Count();
 }
 else
 {
     return dbSet.Count(filter);
 }

이것은 나를 위해 문제를 정렬했습니다. 이것은 DbSet의 다른 방법에도 문제가 될 수 있습니다.


참고로 누군가가 유용하다고 생각할 수도 있습니다. 나는이 오류에 대해 거의 2 일 동안 내 꼬리를 쫓고 있었고 항상 큰 것을 생각하고 문제가 될 수있는 클래스를 찾고 있었고 마침내 매우 어리석은 문제를 발견했으며 mypage.ascx의 내 마크 업 (HTML) 코드에있었습니다. . 문제는 내가 가지고 <asp:EntityDataSource>있었고 이것은 include 속성을 가지고 있고 여기에 나열된 다른 테이블이 있으며 실수로 최근 데이터베이스에서 삭제 된 테이블이 있었고 실수로 다른 엔티티와 함께 ​​null을 반환하는 경우가 있습니다. 방금 포함 목록에서 바보 같은 테이블을 제거했으며 계속 진행할 수 있습니다. 이것이 누군가를 도울 수 있기를 바랍니다.


다른 사람이 DB First Entity Framework 설정과 관련하여 여기에 문제가 발생하는 경우.

Long story short, I needed to overload the Entities constructor to accept a connection string, the reason being the ability to use Asp.Net Core dependency injection container pulling the connection string from appsettings.json, rather than magically getting it from the App.config file when calling the parameterless constructor.

I forgot to add the calls to initialize my DbSets in the new overload. So the auto-generated parameter-less constructor looked something like this:

    public MyEntities()
        : base("name=MyEntity")
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

And my new overload looked like this:

    public MyEntities(string connectionString)
        : base(connectionString)
    {
    }

The solution was to add those initializers that the auto-generated code takes care of, a simple missed step:

     public MyEntities(string connectionString)
        : base(connectionString)
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

This really threw me for a loop because some calls in our Respository that used the DbContext worked fine (the ones that didn't need those initialized DBSets), and the others throw the runtime error described in the OP.


Make sure you are injecting the repository into the service's constructor. That solved it for me. ::smacks forehead::


Resolved with the following solution

  1. Right click on the edmx file, select Open with, XML editor
  2. Locate the entity in the edmx:StorageModels element
  3. Remove the DefiningQuery entirely
  4. Rename the store:Schema="dbo" to Schema="dbo" (if exists)
  5. Remove the store:Name property

It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).


In MVC, View screen is calling method which is in Controller or Repository.cs and assigning return value to any control in CSHTML but that method is actually not implemented in .cs/controller, then CSHTML will throw the NULL parameter exception


I got this error when I had an invalid Type for an entity property.

public Type ObjectType {get;set;}

When I removed the property the error stopped occurring.


In my case, the problem popped up while configuring the web application on IIS, When the update command on any record was fired this error got generated.

It was a permission issue on App_Data which set to read-only. Right-click the folder, uncheck the Read-only checkbox and you are done. By the way, for testing purpose, I was using the localdb database which was in App_Data folder.


My mistake was forgetting to add the .ThenInclude(s => s.SubChildEntities) onto the parent .Include(c => c.SubChildEntities) to the Controller action when attempting to call the SubChildEntities in the Razor view.

var <parent> = await _context.Parent
            .Include(c => c.<ChildEntities>)
            .ThenInclude(s => s.<SubChildEntities>)
            .SingleOrDefaultAsync(m => m.Id == id);

It should be noted that Visual Studio 2017 Community's IntelliSense doesn't pick up the SubChildEntities object in the lambda expression in the .ThenInclude(). It does successfully compile and execute though.


I know this is a long way from the year 2013 of the question, but this symptom can show up if you don't have lazy loading enabled when migrating an ASP.NET 5 app to ASP.NET Core, and then trying to upgrade to Entity Framework Core 2.x (from EF 6). Entity Framework Core has moved lazy loading proxy support to a separate package, so you have to install it.

This is particularly true if all you have loaded is an Entity Framework Core Sql Server package (which turns on Entity Framework just fine).

After installing the proxies package, then, as the docs say, invoke .UseLazyLoadingProxies() on the DbContext options builder (in your Startup DI setup section, or wherever you configure your DbContext), and the navigational property that was throwing the above exception will stop throwing it, and will work as Entity Framework 6 used to.


I just got this exact error in .Net Core 2.2 Entity Framework because I didn't have the set; in my DbContext like so:

public DbSet<Account> Account { get; }

changed to:

public DbSet<Account> Account { get; set;}

However, it didn't show the exception until I tried to use a linq query with Where() and Select() as others had mentioned above.

I was trying to set the DbSet as read only. I'll keep trying...


Take a Row in the database and make all the column null in that row like this "NULL".Now pass that NULL value using try catch or if else.

참고URL : https://stackoverflow.com/questions/16281133/value-cannot-be-null-parameter-name-source

반응형