I have 2 entities Documents(Id,Number,Content,Date_Added) and Adocuments(archives of documents)(Ida,Number,Content,Date_Added) and I want to move the Documents (for example) from march in my archive entity. My tables have the same fields.
Select part
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
Insert part
//WPFModel.Adocument.Insert/Add(qry);
After that I can delete the march documents from the Document entity.
How can I move the data(qry) from Documents to Adocuments? (will there be any problems with the uniqueness of my Id ?)
you can try this :
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
foreach (Document doc in qryluna)
{
Adocument newadoc = new Adocument();
newadoc.IdA = doc.Id;
newadoc.Nr_intern = doc.Nr_intern;
newadoc.Obiect = doc.Obiect;
newadoc.Data_Added = doc.Data_Added ;
WPFModel.Adocument.AddObject(newadoc);
WPFModel.Document.DeleteObject(doc);
}
WPFModel.SaveChanges();
you can do trying downcasting the element result from query, if it will not run you should take each element and copy to a new bject, than you can save it in hystory table.
The id could be a problem, because if you settled the id as autoincrement (identity on sql server) of course the db will try to release a new id, instead your old one.
The most secure task that you should do is to questy the first entity, take each values and fill a new hystorical entity (related to the hystory table) and save it.
I guess that you could have the second table (Adocuments) with those fields:
id (your table identity id)
ida (your id copied from Documents table, to really maintain the history)
number
content
date_added
I hope this is useful for you :)
Related
I have a dax measure . This measure have 1 data . This is "GOOGLE";"YOUTUBE";"AMAZON"
I want to use this 1 line string result in FILTER.
CALCULATE(SUM(_TABLE);_TABLE.COMPANIESNAME; FILTER(_TABLE.COMPANIESNAME IN { mymeasure } ))
Does anyone can help me solve this problem ?
Thank you for help
There are probably way better ways to do what you want. You are treating Power BI like a relational database when you should be using it like a Star Schema. But without more info, I'm just going to answer the question.
Here's my sample table:
// Table
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcsxNrMrPU9JRMlSK1YlWcs/PT89JBXKNwNzI/NKQ0iQQ3xjMd0tMTk3Kz88GCpgoxcYCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Company = _t, Count = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Count", Int64.Type}})
in
#"Changed Type"
I don't have your DAX measure or its name, so I'm using this:
CompanyList = """Google"";""YouTube"";""Amazon"""
Just to prove it's the same as your measure, here it is in the report:
From this post I created a DAX formula that will parse your DAX value into a table with one row for each company name. Add this as a DAX table from Modeling > New Table. I named mine "Filtered table".
Filtered table = VAR CommaSeparatedList = [CompanyList]
VAR BarSeparatedList =
SUBSTITUTE ( CommaSeparatedList, ";", "|" )
VAR Length =
PATHLENGTH ( BarSeparatedList )
VAR Result =
SELECTCOLUMNS (
GENERATESERIES ( 1, Length ),
"Company", SUBSTITUTE( PATHITEM ( BarSeparatedList, [Value] ), """", "")
)
RETURN
Result
Here's what the table looks like:
Add a relationship between the two tables like this (Modeling > Manage relationships > New...):
Then add a DAX column to the filtered table by selecting the table and then Modeling > New Column
Count = CALCULATE(SUM('Table'[Count]))
You can total it up with this DAX measure:
Filtered total = SUM('Filtered table'[Count])
Change the CompanyList measure, and result will update:
I'm getting strange results using trying to do a simple query against a date column using Linq and EF Core.
If I run the query using a date from a list of DateTime I get no results. If I substitute DateTime.Now and add a negative number of days so that if matches the date in the list of DateTimes then the query returns results as expected.
So what is the difference between DateTime.Now and another DateTime object?
In practice, why would this work (rewinding now by 30 days in the first example gives the same date as datesToCheck[0] in the second):
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > DateTime.Now.AddDays(-30))
select r;
But not this:
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > datesToCheck[0])
select r;
The database is SQL Server 2017, the column is a non-nullable smalldatetime
The datesToCheck list is generated thus:
var datesToCheck = new List<DateTime>();
var startDate = DateTime.Now;
//get Monday date three weeks ago
if (DateTime.Now.DayOfWeek != DayOfWeek.Monday)
{
while (startDate.DayOfWeek != DayOfWeek.Monday)
{
startDate = startDate.AddDays(-1);
}
}
startDate = startDate.AddDays(-21);
while (startDate < DateTime.Now)
{
if (startDate.DayOfWeek != DayOfWeek.Saturday || startDate.DayOfWeek != DayOfWeek.Sunday)
{
datesToCheck.Add(startDate);
startDate = startDate.AddDays(1);
}
}
The same behavior exists in EF6 and, as far as I know, all versions of EF. Basically, the compiler isn't clever enough to decide if datesToCheck[0] should be evaluated or converted to SQL. The query will work if you store the value in a variable and then use the variable in the LINQ query. See also: Why can't we use arrays in Entity Framework queries?
You probably have some datatype issue, Try:
DateTime datesToCheck = DateTime.Now.AddDays(-30);
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > datesToCheck )
select r;
Below is the function that inserts my data.
using (SqlCommand insSwipeDataCommand = connection.CreateCommand())
{
insSwipeDataCommand.Transaction = transaction;
insSwipeDataCommand.CommandType = CommandType.StoredProcedure;
insSwipeDataCommand.CommandText = "dbo.insSwipeData_sp";
SqlParameter attendeeTableParam = insSwipeDataCommand.Parameters.Add("#AttendeeTable", SqlDbType.Structured);
attendeeTableParam.Value = this.dataTable;
attendeeTableParam.TypeName = "AttendeeTableType";
// add orgid parameter
insSwipeDataCommand.Parameters.Add("#orgId", SqlDbType.UniqueIdentifier).Value = this.organizationId;
insSwipeDataCommand.ExecuteNonQuery();
}
insSwipeData_sp
create PROC dbo.insSwipeData_sp
(#AttendeeTable AttendeeTableType READONLY
,#orgId UNIQUEIDENTIFIER
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #enteredUserId UNIQUEIDENTIFIER
SET #enteredUserId = 'xxxxxxxxx-xxxx-xxx-xxxx-xxxxxxxxxx'
-- Delete old Swipe records
DELETE FROM dbo.swipeData_tbl
WHERE orgId = #orgId
-- CREATE Swipe Records
INSERT INTO dbo.swipeData_tbl
(orgId, sdid, rawData, enteredUserId, enteredUtc, manualEntry)
SELECT #orgId, attendeeId, barcode
,#enteredUserId, GETUTCDATE(), 0 -- Consider ( datepart , date ) if date here is needed as NVARCHAR
FROM #AttendeeTable
WHERE barcode IS NOT NULL and LTRIM(RTRIM(barcode)) <> '';
END
Here is an image of my AttendeeTableType schema.
and here is an image of my this.datatable that i am using for my attendeeTableParam
On the insSwipeDataCommand.ExecuteNonQuery(); line i get the following error.
The data for table-valued parameter "#AttendeeTable" doesn't conform to the table type of the parameter.
Per the error, your data does not conform to the table type exactly. Note "exactly" -- if you do not specify types for the columns, they will be inferred, and they can easily be inferred incorrectly. The best approach here is to create a table that you know matches the table type definition:
var dt = new DataTable();
dt.Columns.Add("firstName", typeof(string)).MaxLength = 100;
dt.Columns.Add("lastName", typeof(string)).MaxLength = 100;
dt.Columns.Add("studentId", typeof(string)).MaxLength = 10;
dt.Columns.Add("email", typeof(string)).MaxLength = 100;
dt.Columns.Add("barcode", typeof(string)).MaxLength = 100;
dt.Columns.Add("dob", typeof(string)).MaxLength = 200;
dt.Columns.Add("major", typeof(string)).MaxLength = 200;
dt.Columns.Add("gender", typeof(string)).MaxLength = 200;
dt.Columns.Add("classCode", typeof(string)).MaxLength = 15;
dt.Columns.Add("currentclassCode", typeof(string)).MaxLength = 15;
dt.Columns.Add("entranceCode", typeof(string)).MaxLength = 15;
dt.Columns.Add("attendeeId", typeof(Guid));
And then use .Clone() to create a new table with the correct schema when you need to insert data. This way, if you have a type or length mismatch, it will be caught on the client end.
There is another approach you can take that does not rely on embedding the table definition into the application, which is fetching it from the database. There are pros and cons to this -- it requires an extra roundtrip to the database and it's not as easy to spot mistakes in the application logic if the types or columns don't match, but it does give you additional flexibility to change the type without having to change the application (adding a new, nullable column, for example).
var dt = new DataTable();
using (var connection = new SqlConnection(...)) {
connection.Open();
using (var command = new SqlCommand()) {
command.Connection = connection;
command.CommandText = "DECLARE #t dbo.AttendeeTableType; SELECT * FROM #t;"
using (var reader = command.ExecuteReader()) {
dt.Load(reader);
}
}
}
Obviously you probably want to cache the results of this and .Clone(), rather than doing it for every command involving the table type parameter.
I reached this page while searching for similar issue that I was experiencing, but none of the replies did help me. After some head beating I found that the error is being generated in case when the data table being passed from the code has some data that does not match the TVP type specification.
For example if you defined the following type:
CREATE TYPE EmployeeType AS TABLE
(
EmpID BigInt, EmpName VARCHAR(100)
)
and suppose the data table that you are passing has (say) one EmpName that has more than 100 characters then "*** does not conform to table type" error is generated.
This solved my issue. Hope it will help others as well.
Even though Jeroen Mostert answer helped me solve one piece of the puzzle, this error was still popping up.
Here is what I learned;
Datatable created and passed as table value param should
correspond to the sequence / order of field in table value type defined
in sql.
So if your table type looks like below :
CREATE TYPE [dbo].[tvp_mytabletype] AS TABLE(
[ID] BIGINT,
[AddressCode] BIGINT,
[Address] NVARCHAR(200) NOT NULL
)
then define your DT with columns in exact same order/sequence like below :
DataTable dataTable = new DataTable();
//DataTable definition
dataTable.Columns.Add("ID", typeof(long));
dataTable.Columns.Add("AddressCode", typeof(long));
dataTable.Columns.Add("Address", typeof(string)).MaxLength = 200;
Your attendeeId is looks strange. It must be Guid in C# side.
I´m trying to optimize some process in my application but I´m stuck with this problem. My application is working so the entity mapping is correct. Simplifying what I´m trying to do is this:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= {0}", purgePivot);
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
I´m selecting some data I want to delete from one table, storing it in a temporary table so that I can use this temporary table in other queries to exclude related data.
The problem is, when I try to use the temporary table I´m receiving the exception SqlException: "Invalid object name '#NewLegs'."
Thank you for your time.
You can merge the query like this.
And count returns int, not long.
COUNT always returns an int data type value. - MSDN
var query = string.Format("{0} {1}",
#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= #STDUTC",
#"select count(*) from #NewLegs")
var d = offCtx.Database.SqlQuery<int>(query, new SqlParameter("STDUTC", purgePivot))
.FirstOrDefault();
I realy don´t know why but removing the parameter and adding it in the query solved the problem.
The code below works fine:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= " + purgePivot.toString("yyyy-mm-dd HH:mm:ss");
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
Our table structure looks like below:
appointmentID
1abc --------------->1
1abc (latest) ------------>2
1hjt
990aa
990aa
990aa (latest
DateTime start = DateTime.Now.AddDays(0);
DateTime end = DateTime.Now.AddDays(7));
List<JobCustomers> appointments = objectContext.JobCustomers.Where(
a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId)).ToList();
foreach (JobCustomers appointmentItem in appointments) {
// HERE I WANT TO WRITE SOME CODE
-- WHEN WE ARE INSERTING NEW RECORD OF A SAME ID EX "1abc" IT MUST
COMPARE WITH LATEST RECORD "-----2>
}
My requirement: if there are morethan 1 rows with same id then I need to bring latest record by appointment id something like below
List<JobCustomers> appointments = objectContext.JobCustomers.Where(
a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId).**take(0**)).ToList();
In simple words : Using LINQ when we are inserting a new record with same id we need to compare with a last inserted record
Neither LINQ nor SQL don't know in which order you insert data, you need to have an extra field to save this order (could be a date, or an autonumeric). Once you have that, you will be able to use:
YourList.OrderBy(i => i.Id).ThenByDescending(i => i.YourColumnToSaveOrder)
var latestAppts = appointments.GroupBy(x => x.AppointmentId)
.Select(g => g.Last());
If I'm reading this correctly, you're trying to specifically grab the latest record with the same ID that's being brought That would simply need to be done with LINQ's LastOrDefault extension method:
//Variable 'yourNewRecord' is what you're about to enter into the database
var latestAppt = objectContext.JobCustomers
.LastOrDefault(a => a.StartTime >= start &&
a.EndTime <= end &&
a.AppointmentID.Equals(yourNewRecord.AppointmentID)
EDIT: For more information about LastOrDefault, please look at the MSDN link here.