简体   繁体   中英

Entity Framework 4.0/ How to concatenate string from date and time

I have this table

CREATE TABLE Receipt
(
    id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    idcustom INT NOT NULL,
    idstaff INT NOT NULL,
    Daypayat DATE NOT NULL,
    Timepayat TIME NOT NULL,
    total INT NOT NULL
)

And I want to concatenate Daypayat with Timepayat like DateTime (dd/MM/yyyy hh:mm)

Firstly do the concatenation and save the result in the specific column in SQL using the following method.

select cast(@date+' '+@time  as datetime)

or you can do this to convert,

select cast(@date as datetime)+@time

and then use Datetime struct in C# to get result.

Formatting is a view / consumer concern, it should not be a domain one. The entity should expose DayPayAt and TimePayAt as their respective types. (DateTime and DateTime / Timespan) When you query the data, project it to a ViewModel/DTO which can combine those values into a PayAt DateTime, then let your view format that how you desire.

So if your entity has:

public DateTime DayPayAt { get; set; }
public Timespan TimePayAt { get; set; }

your query would be:

var receipt = context.Receipts
    .Where(/*conditions...*/)
    .Select(x => new 
    {
        // other fields or related data as needed.
        x.Daypayat,
        x.Timepayat
    }).ToList() // Materialize our query...
    .Select(x => new ReceiptViewModel
    {
        // Copy related data from results...
        PayAt = x.DayPayAt.Add(x.Timepayat);
    }).ToList();

Then in your view you can format "PayAt" using whatever custom or standard formatting string you want. @Model.PayAt.ToString("g") for instance would give you the standard short date/time format for your region, or use a custom format string for something specific.

The above example does a double-projection, one to get the raw fields of interest from our entity, the second to project to the view model. This may not be necessary depending if EF can perform a DateTime.Add . (I don't believe so)

If Timepayat in the entity maps to a DateTime field, (Ie 0000-00-00T14:20:00) then the PayAt conversion would be:

        PayAt = x.DayPayAt.Add(x.Timepayat.TimeOfDay);

An alternative if you want to return the entity and handle it there is to use an unmapped property on the Receipt entity for PayAt that composes the DateTime. The caveat of that approach is that you need to remember not to reference any unmapped property in a Linq expression since it cannot be translated to SQL.

public class Receipt
{
    // Mapped properties...
    public DateTime Daypayat { get; set; }
    public TImespan Timepayat { get; set; }

    [NotMapped]
    public DateTime PayAt
    {
        get { return Daypayat.Add(Timepayat); }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM