how to insert null or valid value in nullable column of database in EF 4.1 - entity-framework

I am in scenerio where I need to inset a dateTime value in the database using the EF 4.1.
DateColumn in database in Nullable.
While creating the entity i am filling it as,
DTCLOSE = referenceProblemLog.DateClosed.HasValue ?
referenceProblemLog.DateClosed.Value.ToFeedFormatString() :
System.DBNull.Value.ToString(),
where ToFeedFormatString is an extension method.
Now problem i observed is, if I have a proper value then it is inserted correctly but
when i dont have a proper date value, i want to insert NULL in database column. However EF is saving column with Empty string
I tried to change the StoreGeneratedPattern for the field to "Identity" but problem with it is, I cant assign value to DTCLose field.
How can i have both the things?
1. EF should insert NULL in database when proper value is not there
2. proper value otherwise
Please help
Thanks
Anup

This is wrong System.DBNull.Value.ToString() because at the end you will have string object, ToString() never returns null.
You have to set DTCLOSE = null
Also, with EF you don't have to use DBNull, you just define nullable property and set it null

You Can use this :
Nullable<DateTime> date=null;
var entity = new Model()
{
GoDate = date
};
DataContext.Models.Add(entity);
DataContext.SaveChanges();

Related

EF Core completely ignores my selected properties in select

As I understand it, the following code should generate a query containing only the RouteId, RouteNo, and ShipId
var tow = (from t in _context.AllTowData
where t.RouteId == id
orderby t.RouteNo descending
select new TowDefaults {
Id = t.RouteId,
TowNo = t.RouteNo,
ShipId = t.ShipId,
LastTow = t.RouteNo
})
.FirstOrDefault();
However, I get:
SELECT v.route_id, v.route_no, v.tow_id, v.analysis_complete, v.checks_complete, v.cpr_id, v.date_created, v.date_last_modified, v.factor, v.fromportname, v.instrument_data_file, v.instrument_id, v.internal_number, v.mastername, v.message, v.miles_per_division, v.month, v.number_of_samples, v.number_of_samples_analysed_fully, v.prop_setting, v.route_status, v.sampled_mileage, v.serial_no_per_calendar_month, v.ship_speed, v.silk_reading_end, v.silk_reading_start, v.toportname, v.tow_mileage, v.validity, v.year
FROM view_all_tow_data AS v
WHERE v.route_id = '#__id_0'
ORDER BY v.route_no DESC
LIMIT 1
That's every column except the explicitly requested ShipId! What am I doing wrong?
This happens using both a SQL Server and a PostGres database
The property ShipIdis not mapped, either by a [NotMapped] annotation or a mapping instruction. As far as EF is concerned, the property doesn't exist. This has two effects:
EF "notices" that there's an unknown part the final Select and it switches to client-side evaluation (because it's a final Select). Which means: it translates the query before the Select into SQL which doesn't contain the ShipId column, executes it, and materializes full AllTowData entities.
It evaluates the Select client-side and returns the requested TowDefaults objects in which ShipId has its default value, or any value you initialize in C# code, but nothing from the database.
You can verify this by checking _context.AllTowData.Local after the query: it will contain all AllTowData entities that pass the filter.
From your question it's impossible to tell what you should do. Maybe you can map the property to a column in the view. If not, you should remove it from the LINQ query. Using it in LINQ anywhere but in a final Select will cause a runtime exception.

mybatis - Passing multiple parameters on #One annotation

I am trying to access a table in my Secondary DB whose name I am obtaining from my Primary DB. My difficulty is to pass the "DB-Name" as a parameter into my secondary query, (BTW I am using MyBatis annotation based Mappers).
This is my Mapper
#SelectProvider(type = DealerQueryBuilder.class, method = "retrieveDealerListQuery")
#Results({
#Result(property="dealerID", column="frm_dealer_master_id"),
#Result(property="dealerTypeID", column="frm_dealer_type_id", one=#One(select="retrieveDealerTypeDAO")),
#Result(property="dealerName", column="frm_dealer_name")
})
public List<Dealer> retrieveDealerListDAO(#Param("firmDBName") String firmDBName);
#Select("SELECT * from ${firmDBName}.frm_dealer_type where frm_dealer_type_id=#{frm_dealer_type_id}")
#Results({
#Result(property="dealerTypeID", column="frm_dealer_type_id"),
#Result(property="dealerType", column="frm_dealer_type")
})
public DealerType retrieveDealerTypeDAO(#Param("firmDBName") String firmDBName, #Param("frm_dealer_type_id") int frm_dealer_type_id);
The firmDBName I have is obtained from my "Primary DB".
If I omit ${firmDBName} in my second query, the query is trying to access my Primary Database and throws out table "PrimaryDB.frm_dealer_type" not found. So it is basically trying to search for a table named "frm_dealer_type" in my Primary DB.
If I try to re-write the #Result like
#Result(property="dealerTypeID", column="firmDBName=firmDBName, frm_dealer_type_id=frm_dealer_type_id", one=#One(select="retrieveDealerTypeDAO")),
It throws an error that Column"firmDBName" does not exist.
Changing ${firmDBName} to #{firmDBName} also did not help.
I did refer to this blog - here
I want a solution to pass my parameter firmDBName from my primary query into secondary query.
The limitation here is that your column must be returned by the first #SELECT.
If you look at the test case here you will see that parent_xxx values returned by the first Select.
Your DealerQueryBuilder must select firmDBName as a return value and your column must map the name of the return column to that.
Your column definition is always wrong, it should be:
{frm_dealer_type_id=frm_dealer_type_id,firmDBName=firmDBName} or whatever it was returned as from your first select.
Again you can refer to the test case I have above as well as the documentation here http://www.mybatis.org/mybatis-3/sqlmap-xml.html#Nested_Select_for_Association

-Infinity added to database for NpgsqlParameter Timestamp field; expecting NULL

I'm inserting a record in my PostgresSQL table passing DBNull.Value for a timestamp without time zone field using a NpgsqlParameter as below:
ncmd.Parameters.Add(new NpgsqlParameter(":EndDate", NpgsqlDbType.Timestamp));
DateTime? dtval = sr.GetDateTime("EndDate");
ncmd.Parameters["EndDate"].IsNullable = true;
if (dtval.HasValue)
ncmd.Parameters["EndDate"].Value = dtval;
else
ncmd.Parameters["EndDate"].Value = DBNull.Value;
When I try to select only those records with null values for the field I use "Select * From "EVAL" Where "EndDate" IS NULL" but nothing is returned. When I read the table data in the pgAdmin I see the value "-infinity" in the field.
Please, could somebody tell me how to pass null values for a NpgsqlParameter?
Thanks in advance,
Danilo da Silva
Sorry, I've found my error. When I read the data to be inserted from a datareader, I was getting a default value for the DateTime field when it is null and so I was inserting default(DateTime) not DBNull.Value. Now I'm testing dtval.HasValue && dtval != default(DateTime) and all goes right. Thanks.

Using max() function with entity framework throws an exception

So I need to get the max value of a column (or the last one) using entity framework and both of these queries throw exceptions:
(The ID I'm trying to retrieve is of type varchar, but it works in raw sql, I think
it should work here too)
This one:
string maxCurrentID = db.reservations.Max().ReservationID;
Throws this:
The specified method 'EntityClub_.reservacion Maxreservacion' on the type 'System.Linq.Queryable' cannot be translated into a LINQ to Entities store expression because no overload matches the passed arguments.
and this one:
string maxCurrentID = db.reservations.LastOrDefault().ReservationID;
LINQ to Entities does not recognize the method 'EntityClub_.reservacion LastOrDefaultreservacion' method, and this method cannot be translated into a store expression.
How can I obtain the expected values?
var maxReservationId=db.reservations.Max(u =>(int?)u.ReservationID) ?? 0;
if there is no data in table it replaces null with 0
You aren't asking for the highest ReservationID, you're trying to get the highest Reservation, and getting its ReservationID. EF does not understand what "the highest Reservation" means.
var maxReservationID = db.reservations.Max(r => r.ReservationID);
or
var maxReservationID = db.reservations.Select(r => r.ReservationID).Max();
should work.

I dont want to insert the PK val.But - Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF

I am using the Entity Framework to update my database.
The Employee table has an employeeId primary key field.
When I instantiate an employee object, the employeeId defaults to zero.
I want to insert the employee object into the database, ignoring the primary key value of zero.
Yet I get this exception;
Cannot insert explicit value for identity column in table 'Employees' when IDENTITY_INSERT is set to OFF.
What should I be doing to stop this?
public void Add()
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
// Set default values
this.StartDate = DateTime.Now;
// Start date now
this.SHP_UserRoleId = db.SHP_UserRoles.Where(x => x.RoleName == "Employee").Single().UserRoleId;
// Default user role is "Employee". This can be changed later.
this.DepartmentId = 1;
// This is a temporary fix.
db.AddToEmployees(this);
//db.Employees.AddObject(this);
db.SaveChanges();
}
}
I fixed the problem.
I updated the database and I forgot to update my edmx file to reflect that change.